va9999 :
I have a database table which looks like the attached image
enter image description here I need to query this and be able to show output in the format of BookID, Genre1, Genre2, Genre3
I have read some previous posts on pivoting / use of the MAX function but I am still struggling, I am new to this.
Gordon Linoff :
You can use row_number()
and conditional aggregation:
select bookId,
max(case when seqnum = 1 then genre end) as genre_1,
max(case when seqnum = 2 then genre end) as genre_2,
max(case when seqnum = 3 then genre end) as genre_3
from (select bg.*,
row_number() over (partition by bookId order by genre) as seqnum
from bookGenres
) bg
group by bookId;