sp_Query_Pivot.sql

This script generates simple pivot tables on data and outputs the final SQL statement via Print.

For example, given data as shown below:

ID          year        type        amt
———– ———– ———– ———–
7 1999 1 23
8 1999 2 44
9 1999 3 55
10 2000 1 66
11 2000 2 77
12 2000 3 88
13 1999 1 11

… you can pivot the data to show the years down the side and the types across the top…

year        1           2           3           RowTotal
———– ———– ———– ———– ———–
1999 34 44 55 133
2000 66 77 88 231

… and get the SQL which would produce this table


SELECT Pivot_Data.*,
(Pivot_Data.[1] + Pivot_Data.[2] + Pivot_Data.[3]) AS RowTotal
FROM (SELECT [year],
SUM(CASE [type] WHEN ‘1’ THEN [amt] ELSE 0 END) AS [1],
SUM(CASE [type] WHEN ‘2’ THEN [amt] ELSE 0 END) AS [2],
SUM(CASE [type] WHEN ‘3’ THEN [amt] ELSE 0 END) AS [3]
FROM (select * from zzjunk) AS Base_Data
GROUP BY [year]) AS Pivot_Data

.. by calling the procedure as shown below:


exec sp_Query_Pivot ‘select * from zzjunk’, ‘[year]’, ‘[type]’,
‘Select distinct [type] from zzjunk’, ‘SUM’, ‘[amt]’, ‘Y’

Author: Jeff Zohrab

Download Script:
sp_Query_Pivot.sql
sp_Query_Pivot_TEST.sql



Disclaimer:
We hope that the information on these script pages is
valuable to you. Your use of the information contained in these pages,
however, is at your sole risk. All information on these pages is provided
“as -is”, without any warranty, whether express or implied, of its accuracy,
completeness, or fitness for a particular purpose…

Disclaimer Continued

Back to Database Journal Home

Latest Articles