简体   繁体   中英

SQL Joining between same table for multiple rows

This is probably simple but im having a mental blank 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.

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?

Thanks

You can use conditional aggregation via case statements:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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