Skip to content
Advertisement

Pivot data T-SQL

I have the following table:

enter image description here

I want to pivot it to the following table:

enter image description here

I tried to work with the following example: https://www.sqlshack.com/dynamic-pivot-tables-in-sql-server/ But in this case a SUM operator is mandatory. I don’t want to use the SUM operator for my data.

What would be the best approach to go. Eventually I want to use the data again, I want to prevent that I need to make a lot of “left join” statements like the following:

I am able to unpivot the numbercat & number with the following code:

What should I do to also incorporate the Namecat & namevalue data?

Advertisement

Answer

I find that conditional aggregation is usually simpler and more versatile than pivot:

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