简体   繁体   English

同一表之间多行的SQL连接

[英]SQL Joining between same table for multiple rows

This is probably simple but im having a mental blank atm. 这可能很简单,但是我的脑子里有空白的atm。

Table A

ID       Seq    Txt
---------------------------
10        0      Orange
10        1      Banana
20        0      Mango
30        0      Apple
30        1      Grape
30        2      Pineaple

I want to be able to group all IDs and display them on the one row. 我希望能够对所有ID进行分组并将它们显示在一行上。

ie

ID      Seq1    Txt1    Seq2    Txt2
-------------------------------------
10       0       Orange  1       Banana
20       0       Mango   null    null
.. 30 etc

How do I go about this? 我该怎么办? I perform a join on itself and do an OR on the Seq number? 我对自己执行连接,并对Seq编号执行OR。

Thanks 谢谢

You can use conditional aggregation via case statements: 您可以通过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

But you'll have to add more case statements to the above if seq can go beyond the # 2. 但是,如果seq可以超出#2,则必须在上面添加更多case语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM