Thursday, May 26, 2011

Overcoming the Limitation of PIVOT for Strings


This example will use the following table:SELECT Record, Variable, VariableValue
FROM #temp123
Here is a resultset from the above SELECT query:
RecordVariableVariableValue
11First Value
12Second Value
13Third Value
14Fourth Value
21First Value
22Second Value
23Third Value
27Seventh Value
28Eighth Value
39Ninth Value
42Second Value
45Fifth Value
410Tenth Value

Now we can use the PIVOT Keyword to create a crosstab result. This will make columns for 'Variable': 1,2,3,4,5,6,7,8. A single row will be displayed for each record.
Note: We are not making columns for 'Variable' 9 and 10.

SELECT *
FROM #temp123
PIVOT
(
  MAX(VaribleValue)
  FOR [Variable] IN ([1],[2],[3],[4],[5],[6],[7],[8])
)
AS p
Here is a resultset from the above PIVOT query:
Record12345678
1First ValueSecond ValueThird ValueFourth Valuenullnullnullnull
2First ValueSecond ValueThird ValuenullnullnullSeventh ValueEighth Value
3nullnullnullnullnullnullnullnull
4nullSecond ValuenullnullFifth Valuenullnullnull




Dynamic PIVOT with Grand Total Row - PIVOT without specifying columns


This is the same as the above dynamic pivot, except it also adds a Grand Total Row to the dataset. This was created in response to a user's question.
DECLARE @columns VARCHAR(8000)
DECLARE @TotalColumns VARCHAR(8000)

SELECT
@columns = COALESCE(@columns + ',[' + cast(Variable as varchar) + ']',
'[' + cast(Variable as varchar)+ ']'),

@TotalColumns =
COALESCE(@TotalColumns + ',SUM([' + cast(Variable as varchar) + ']) as [' + cast(Variable as varchar) + ']',
'SUM([' + cast(Variable as varchar)+ ']) as [' + cast(Variable as varchar)+ ']')

FROM #temp123
GROUP BY Variable

DECLARE @query VARCHAR(8000)
SET @query = '
SELECT *
FROM #temp123
PIVOT
(
MAX(VaribleValue)
FOR [Variable]
IN (' + @columns + ')
)
AS p
UNION
SELECT ''Grand Total'',' + @TotalColumns + '
FROM #temp123
PIVOT
(
MAX(VaribleValue)
FOR [Variable]
IN (' + @columns + ')
)
AS total
'

EXECUTE(@query)
The above script will first define two variables for storing the new column list and the Total select columns.
The next step will select each 'Variable' field and append it to the @columns variable, it will also place brackets around each field.
It will also select each 'Variable' field and append it to the @TotalColumns variable with the SUM() function around it as well as specifying the name of the field.
The next step defines the variable for storing the query.
The fourth step builds the query string and stores it in the query variable
The last step runs the query using the EXECUTE function

Here is a resultset from the above Dynamic PIVOT query:
CountrySalesExpensesTaxesProfit
North America20000001250000250000500000
Europe25000001250000500000750000
South America500000250000nullnull
Asia800000350000100000null
Grand Total580000031000008500001250000

No comments: