将SQL行转换为列

时间:2014-07-29 23:07:32

标签: mysql sql

这是我的表:

id | num | comment
---+-----+--------
 3 |  10 | hello
 3 |  20 | pls
 3 |  30 | respond
 7 |  10 | leet
 7 |  20 | hax
 7 |  30 | zor

如何以这种方式查询:

id | first | second | third
---+-------+--------+--------
 3 | hello |  pls   | respond
 7 | leet  |  hax   | zor

1 个答案:

答案 0 :(得分:2)

如果num列不能可靠地始终从10开始并以10递增,则可以使用以下命令建立在每次ID更改时重新启动的行号,这样您就可以将rownumbers与条件结合使用聚合以显示每条评论。以下内容适用于每个ID最多10条评论,而NUM列不一定是10/20/30/40/50/60/70/80/90(可能是任何内容)。

如果NUM列可靠地从10开始并且上升10,则会询问并回答此问题:How to pivot rows into columns (custom pivoting)

select id,
       max(case when row_number = 1 then comment else null end) as c01,
       max(case when row_number = 2 then comment else null end) as c02,
       max(case when row_number = 3 then comment else null end) as c03,
       max(case when row_number = 4 then comment else null end) as c04,
       max(case when row_number = 5 then comment else null end) as c05,
       max(case when row_number = 6 then comment else null end) as c06,
       max(case when row_number = 7 then comment else null end) as c07,
       max(case when row_number = 8 then comment else null end) as c08,
       max(case when row_number = 9 then comment else null end) as c09,
       max(case when row_number = 10 then comment else null end) as c10
from(
select @row_number := case when @prev_val = id then @row_number+1 else 1 end as row_number,
       id,
       comment,
       @prev_val:=id as prev_val
from tbl, (select @row_number:=0,@prev_val:='') x
order by id, num) x
group by id
order by id