I need some help on SQL
as this kind of selecting is beyond my knowledge. The result of the select should be in one row as it is shown in the picture. Can someone provide any ideas on how to achieve this?
if col_name1 =AA -> add col_name2 as value col_name5
if col_name1 =BB -> add col_name3 value as col_name6
if col_name1 =CC -> add col_name4 value of first CC (c31) as col_name7 and col_name4 of second CC (c31) value as col_name8
original table might not have all 4 ids
Best Answer
I'm making some assumptions about how your data is ordered (do all BB's come after AA's ordered by Id; do all CC's come after BB's ordered by Id), etc. You also don't say what you want for the ID column in the final result, so I didn't include that column.
By using a Common Table Expression and the Row_Number Window Function, I'm added a sequential row number to each of your original rows.
Here's a demo set up script:
produces
From your question, it appears that you want
col_name7
to be the first CC value,col_name8
to be the next CC value,col_name9
to be the next CC value andcol_name10
to be the last CC value. I'm assuming there will always be an 'AA' and a 'BB', so the first CC row is row number 3, the next CC row will be 4 and so on.Putting it all together