How can you manage to make a 'group by' on one column and still get data (the real data, not a 'sum') on the others?
Let me show an example of what I'd like to do:
Suppose Table A, with index on 'Group', a simple select * from A
gives:
Group Album
---------------- ---------------
ABBA Waterloo
AC/DC Back in Black
ABBA Voulez-vous
ABBA Super Trooper
Imagine Dragons Night Visions
AC/DC Highway to Hell
ABBA The Visitors
I'd like to have the end result as following (knowing that I cannot have more than 4 albums for a group ... for now I guess):
Group Album1 Album2 Album3 Album4
---------------- --------------- --------------- --------------- ---------------
ABBA Waterloo Voulez-vous Super Trooper The visitors
AC/DC Back in Black Highway to Hell Null Null
Imagine Dragons Night Visions Null Null Null
So far, the closest I've come to make what I want is something like the following:
select tab4.GROUP,
tab1.ALBUM as PN1,
tab2.ALBUM as PN2,
tab3.ALBUM as PN3,
tab4.ALBUM as PN4
from
(
select A.GROUP, A.ALBUM
from A
where A.ROWID in
(select max(ROWID) from A
where GROUP in (select GROUP from A A group by A.GROUP having count(*) <= 4)
group by GROUP
)
) tab4
left join
(
select A.GROUP, A.ALBUM
from A A
where A.ROWID in
(select max(ROWID) from A
where GROUP in (select GROUP from A A group by A.GROUP having count(*) <= 3)
group by GROUP
)
) tab3 on tab4.GROUP = tab3.GROUP
left join
(
select A.GROUP, A.ALBUM
from A A
where A.ROWID in
(select max(ROWID) from A
where GROUP in (select GROUP from A A group by A.GROUP having count(*) <= 2)
group by GROUP
)
)tab2 on tab4.GROUP = tab2.GROUP
left join
(
select A.GROUP, A.ALBUM
from A A
where A.ROWID in
(select max(ROWID) from A
where GROUP in (select GROUP from A A group by A.GROUP having count(*) <= 1)
group by GROUP
)
) tab1 on tab4.GROUP = tab1.GROUP;
I know why the SQL request above is wrong: the max(rowid)
will remain the same whatever condition on having count(*)
is thrown.
There could be some pivot
to be used, but I sincerely don't see how can it be used as I have only one table and need to get all data.
As furter precision, I don't need the have the result table in a spcific order and I can limit myself to 4 albums because I know each 'Group' won't have more than that ... but I'd appreciate something generic.
EDIT: Ok, seems I have forgotten to clarify that I'm on Oracle 10g (damn this legacy code ^^) so newer functions like PIVOT
won't work.
Also, I'm not looking for a string aggregation like LISTAGG
but really for separate columns.