Hi I have the following table of data
Class | Member | Value
----------------------
c1 | m1 | 10
c1 | m2 | 20
c1 | list | 30
c1 | list | 40
c1 | list | 50
c2 | m1 | 60
c2 | m2 | 70
c2 | list | 80
and would like to pivot the data into this form
Class | Member 1 | Member 2 | List
----------------------------------
c1 | 10 | 20 | 30
c1 | 10 | 20 | 40
c1 | 10 | 20 | 50
c2 | 60 | 70 | 80
a normal pivot using max as the aggregate function would have given me
Class | Member 1 | Member 2 | List
----------------------------------
c1 | 10 | 20 | 50
c2 | 60 | 70 | 80
but I want each of the List values of any Class to be listed out.
Instead of finding alternatives by writing SQL queries full of CASEes e.g CASE Member WHEN ‘m1’ then Value, CASE Member WHEN ‘m2’ then Value, … to achieve what I want, I want to know if there is any chance to use pivot with some tweaks to make it work for my task?
The database is SQL 2008 R2
Thank you
No.
PIVOTis effectively syntactic sugar for doing aggregates aroundCASEexpressions. If the sugar doesn’t work, you need to go back to the longer form.The syntax for
PIVOTis fully described in theFROMclause:And note that
aggregate_functionmust be provided. All aggregate functions in SQL Server operate on any number of input values and produce a single output value. There’s no aggregate which can produce multiple output values, as you would require here.This gives the result you’ve asked for, but does rely on each
Classvalue only having one row for each ofm1andm2:Result:
If there are multiple rows for
m1andm2, and you just want, say, theMAXvalues for them, then you’d makem1andm2in my above query subqueries: