Kambo_Rambo
Kambo_Rambo

Reputation: 1715

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.

i.e.

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

Upvotes: 0

Views: 36

Answers (1)

Brian DeMilia
Brian DeMilia

Reputation: 13248

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.

Upvotes: 1

Related Questions