sp_Query_Pivot.sql | Database Journal

sp_Query_Pivot.sql

Sep 8, 2001
1 minute read

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] WHEN1THEN [amt] ELSE 0 END) AS [1],
     SUM(CASE [type] WHEN2THEN [amt] ELSE 0 END) AS [2],
     SUM(CASE [type] WHEN3THEN [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

Database Journal Logo

DatabaseJournal.com publishes relevant, up-to-date and pragmatic articles on the use of database hardware and management tools and serves as a forum for professional knowledge about proprietary, open source and cloud-based databases--foundational technology for all IT systems. We publish insightful articles about new products, best practices and trends; readers help each other out on various database questions and problems. Database management systems (DBMS) and database security processes are also key areas of focus at DatabaseJournal.com.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.