[英]Select distinct values as distinct columns in the same row
如標題所示,我想選擇不同的值作為同一行中的不同列
例:
ID CATEGORY
1 5
1 6
1 8
2 5
2 7
3 5
我想要這樣的東西:
ID CATEGORY1 CATEGORY2 CATEGORY3
1 5 6 8
2 5 7
3 5
僅在一個查詢中可行嗎?
得到這樣的最簡單的方法是使用group_concat()
:
select id, group_concat(category order by category)
from table t
group by id;
但是,它將創建一列附加值列表,而不是三列。 這足以滿足您的目的嗎?
如果要增加三列,則需要更復雜的語句。 這是使用變量的一種方法:
select id,
max(case when seqnum = 1 then category end) as category1,
max(case when seqnum = 2 then category end) as category2,
max(case when seqnum = 3 then category end) as category3
from (select t.*,
(@rn := if(@id = id, @rn + 1,
if(@id := id, 1, 1)
)
) as seqnum
from table t cross join
(select @rn := 0, @id := NULL) vars
order by id, category
) t
group by id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.