Skip to content
Advertisement

Using PIVOT in conjunction with a total summation in SQL

I have some data with a general structure:

I want to output a single row like:

I can see that the way to approach this is with a PIVOT, but how would I do this whilst also calculating the total?

Thank

Advertisement

Answer

You can use conditional aggregation:

Note: If you have values other than 'X', 'Y', and 'Z', then you might want either:

or:

I am also assuming that the last column is actually for the sum. If you want a string aggregation, then the logic is:

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