[英]SQL Joining between same table for multiple rows
这可能很简单,但是我的脑子里有空白的atm。
Table A
ID Seq Txt
---------------------------
10 0 Orange
10 1 Banana
20 0 Mango
30 0 Apple
30 1 Grape
30 2 Pineaple
我希望能够对所有ID进行分组并将它们显示在一行上。
即
ID Seq1 Txt1 Seq2 Txt2
-------------------------------------
10 0 Orange 1 Banana
20 0 Mango null null
.. 30 etc
我该怎么办? 我对自己执行连接,并对Seq编号执行OR。
谢谢
您可以通过case语句使用条件聚合:
select id,
min(case seq when 0 then 0 end) as seq1,
min(case seq when 0 then txt end) as txt1,
min(case seq when 1 then 1 end) as seq2,
min(case seq when 1 then txt end) as txt2,
min(case seq when 2 then 2 end) as seq3,
min(case seq when 2 then txt end) as txt3
from tbl
group by id
但是,如果seq可以超出#2,则必须在上面添加更多case语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.