search

Home  >  Q&A  >  body text

Subquery - how mysql merges multiple rows of data into multiple columns of one row


The picture shows the data I filtered out. The statement is
select time,wish_num,num from wish_num where time >= '15296000' and time <= '1495382399' group by time, wish_num,
time and wish_num are joint primary keys
Now I hope to merge the data in the same date into one row, such as
Date 1 time 2 times 5 times 10 times 20 times
1495294000 2 2 4 11 2
1495296000 2 2 4 11 2 、
It looks like this format. How can I modify the above statement and perform a subquery?

習慣沉默習慣沉默2742 days ago848

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-24 11:35:01

    The simplest one is group_concat. If the poster doesn’t use it, then he has to use case when. Since the poster’s num after group by does not use an aggregate function, I understand that num has only one value? The sql is as follows

    select time,
    max(case when wish_num=1 then num else 0) '1',
    max(case when wish_num=2 then num else 0) '2',
    max(case when wish_num=5 then num else 0) '5',
    max(case when wish_num=10 then num else 0) '10',
    max(case when wish_num=20 then num else 0) '20'
    from wish_num where time >= '15296000' and time <= '1495382399' group by time;

    reply
    0
  • Cancelreply