Skip to content
Advertisement

Pivoting rows to columns with custom column names in SQL Server

I’m having some difficulty with pivoting rows into columns as I also want to name the columns. Here is my current code, modified:

And my current output:

Just for the sake of shortness, I replaced the actual Message with longmessage1 above. My desired output:

The maximum amount of greetings is six, and if a Message doesn’t have six, I’m fine with the value of, say greeting 4 and 5 to be NULL.

FYI- I am using SQL Server. I think I could somehow use PIVOT to do this but I’m stuck on the custom column name part and if CROSS APPLY was even the right idea. If anyone could offer some suggestions, that’d be terrific. Thank you!

Advertisement

Answer

You can use row_number() and conditional aggregation:

Note: In practice, this will probably preserve the ordering of the values. However that is not guaranteed — based on the documentation.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement