Please Explain The Parts Of A Pivot
Solution 1:
Explanation of the pivot query
FROM
(SELECT OtherID, Val, amount
FROM @randomTable) pThese are the columns that become the "base data" for the pivot. Do not include columns that don't do anything. Just as you don't put non-GROUP BY columns into the SELECT clause, you don't list out unused columns in a PIVOT source.
PIVOT
(
max(amount)
FOR Val IN (Val1, Val2, Val3, Val4, Val5)
) AS PivotTable;
This part says that you are creating 5 new columns named "Val1" through "Val5". These column names represent values in the column Val. So it is expected that your table will contain something like this
otherID Val amount
1 Val1 12 Val2 21 Val3 31 Val1 5
(etc) (this columncontainsoneof Val1 - Val5, ornull)
So you now have 5 new columns that did not exist before. What goes into the column?
- Any column that appears in the OUTPUT that is not a PIVOTed column is a "GROUP BY" column.
- The aggregate function is what collects all the data into the cell that is the CROSS between the GROUP BY columns and the PIVOTED column.
So, to illustrate, using the sample data above, we have otherID=1 and val=Val1. In the output table, there is only one cell representing this combination of Max(amount) for each (otherID/val) combination
otherID Val1 Val2 Val3 Val4 Val5
1 <x> ... ... ... ...
(etc)
For the cell marked <x> , only one value is allowed, so <x> cannot contain multiple amount values. That is the reason why we need to aggregate it, in this case using MAX(amount). So in fact, the output looks like this
(unpivoted columns) (pivoted, creates "new" columns)
otherID | Val1 Val2 Val3 Val4 Val5
1|MAX(amount) Max(amount) << cell value= aggregate function
(etc)
The SELECT statement is what then outputs these columns
SELECT OtherID, Val1, Val2, Val3, Val4, Val5
Post a Comment for "Please Explain The Parts Of A Pivot"