Database Journal
MS SQL Oracle DB2 Access MySQL PostgreSQL Sybase PHP SQL Etc SQL Scripts & Samples Links Database Forum

» Database Journal Home
» Database Articles
» Database Tutorials
MS SQL
Oracle
DB2
MS Access
MySQL
» RESOURCES
Database Tools
SQL Scripts & Samples
Links
» Database Forum
» Sitemap
Free Newsletters:
DatabaseDaily  
News Via RSS Feed


follow us on Twitter
Database Journal |DBA Support |SQLCourse |SQLCourse2
 

Featured Database Articles

SQL Scripts & Samples

Posted Sep 7, 2001

sp_Query_Pivot.sql

By DatabaseJournal.com Staff



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



SQL Scripts & Samples Archives

Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 




Latest Forum Threads
SQL Scripts & Samples Forum
Topic By Replies Updated
sql help!! add 1 August 22nd, 11:58 AM
How To Combine These 2 Queries into 1 Query ? tarek_land 1 June 7th, 08:37 AM
solving query svibuk 1 February 3rd, 06:08 AM
converting from a character string to uniqueidentifier saturnius 4 January 4th, 05:56 AM