Web design and hosting, database, cloud and social media solutions that deliver business results
  • Business Solutions
    • Robotic Process Automation
    • Software
    • Database Consultancy Services
      • Data Integration
      • Datawarehouse Services
      • Power BI
      • Server Upgrade and DBA Services
    • Web Site Design Services
      • Logo Design
      • Payment Gateways
      • Web Localisation and Translation
      • Web Site Optimisation
      • Web Site Security
      • Technical Tools
    • Cloud Services
      • Amazon Web Services
      • Google Cloud Services
      • Microsoft Azure
    • Microsoft Office
    • Social Media Management and Advice Services
  • Academy
    • Our Test Environment
    • Learning Databases
      • The Basics
      • Get Open Query
      • SQL Server Data
      • SQL Server Maintenance
      • Using SQL Server Dates
      • Using SQL Server Functions
      • Using SQL Server Pivot-Unpivot
      • Technical Tools
    • Learning Web Design
      • Building Ousia Content Management System
      • Using ASP-NET
      • Using CSS
      • Using JavaScript
    • Learning Cloud and IT Services
      • Task Scheduler Error 2147943645
      • Requesting SSL and Generation of PFX file in OpenSSL Simple Steps
    • Using Social Media
      • Asking for a Google Review
      • Changing a Facebook account from personal to business
      • Choosing where to focus Social Media effort
      • Social Media Image Sizes
      • Using Meta Data to set Social Media Images
  • About Us
    • Blog
      • Building an entry level gaming machine
      • Google Core Update Jan 2020
      • Hot Chilli Internet Closure
      • How To Choose Content For Your Website Adverts Leaflets
      • Preventing Online Scam
      • Skimmers of the gig economy
      • The most annoying things about websites on the Internet
      • Top 5 websites for free Vector Graphics
    • Careers
      • Translator English-Portuguese
      • Translator English-Spanish
    • Portfolio
    • Team
      • Adrian Anandan
      • Ali Al Amine
      • Ayse Hur
      • Chester Copperpot
      • Deepika Bandaru
      • Gavin Clayton
      • Sai Gangu
      • Suneel Kumar
      • Surya Mukkamala
عربى (AR)Deutsch (DE)English (EN-US)English (EN-GB)हिंदी (HI)italiano (IT)日本語 (JA)

SQL Server using PIVOT and UNPIVOT together

Combining the power of UNPIVOT, and then PIVOT to turn a 12 column table into a 36 table column or more

Aim

Using Pivot/Unpivot

These functions together can be combined into a very powerful procedure.

We are going to take the data set from the UNPIVOT article, which has 12 months of data stored on a by row basis, we are the going to UNPIVOT and convert these columns into dates and finally PIVOT this into a table 36 columns wide.

I have written smaller articles on each of these separately, so make sure you have read them, and then lets jump into the code.

Using UNPIVOT

Quick guide to using UNPIVOT.
More: SQL Server using UNPIVOT to turn columns into rows

Using PIVOT

Quick guide to using PIVOT.
More: SQL Server using PIVOT example

SQL

CREATE TYPE c1bs_UnPivot AS TABLE(UnPivID INT,UnPivMonth DATE,UnPivData INT)GOCREATE FUNCTION c1bs_DateFromParts(@Year SMALLINT,@Month SMALLINT,@Day SMALLINT) RETURNS DATE AS BEGINDECLARE @Date DATE=CONVERT(NVARCHAR(4),@Year)+'-'+CONVERT(NVARCHAR(2),@Month)+'-'+CONVERT(NVARCHAR(2),@Day)RETURN @DateENDGODECLARE @UnPiv TABLE(UnPivID INT,UnPivYear SMALLINT,M1 INT,M2 INT,M3 INT,M4 INT,M5 INT,M6 INT,M7 INT,M8 INT,M9 INT,M10 INT,M11 INT,M12 INT)INSERT INTO @UnPiv(UnPivID,UnPivYear,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12) SELECT 1,2010,1,2,3,4,5,6,7,8,9,10,11,12INSERT INTO @UnPiv(UnPivID,UnPivYear,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12) SELECT 1,2011,1,2,3,4,5,6,7,8,9,10,11,12INSERT INTO @UnPiv(UnPivID,UnPivYear,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12) SELECT 1,2012,1,2,3,4,5,6,7,8,9,10,11,12INSERT INTO @UnPiv(UnPivID,UnPivYear,M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12) SELECT 2,2010,1,2,3,4,5,6,7,8,9,10,11,12
DECLARE @Piv AS c1bs_UnPivotINSERT INTO @PivSELECT UnPivID,dbo.c1bs_DateFromParts(UnPivYear,REPLACE(col,'M',''),1) col,valFROM @UnPivUNPIVOT (Val FOR col IN (M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,M11,M12)) unpiv

In the last statement we have followed the same process as in the UNPIVOT article, declared a temporary table to insert a dummy data set into, and then UNPIVOTED data into a temp table.

SQL

--Complex Pivot - unknown column names--Get Column Names for belowDECLARE @Cols NVARCHAR(MAX),@Sel NVARCHAR(MAX) SELECT @Cols=COALESCE(@Cols+',','')+'['+CONVERT(NVARCHAR(20),UnPivMonth)+']',--Concatenate the Columns@Sel =COALESCE(@Sel +',','')+'ISNULL(['+CONVERT(NVARCHAR(20),UnPivMonth)+'], 0) AS ['+CONVERT(NVARCHAR(20),UnPivMonth)+']' --Concatenate the Columns into a select listFROM @Piv GROUP BY UnPivMonth ORDER BY UnPivMonth
--Columns list displaySELECT @Cols ColumnList,@Sel SelectList
--Complex Pivot SQLDECLARE @Params NVARCHAR(MAX)='@Piv c1bs_UnPivot READONLY'DECLARE @SQL NVARCHAR(MAX)='SELECT [UnPivID],'+@Sel+'FROM @PivPIVOT (SUM(UnPivData)FOR UnPivMonthIN ('+@Cols+')) AS MyTable'
--Execute SQLEXECUTE sp_executesql @SQL,--SQL String from above@Params,--Parameter list@Piv--Temp Table needs to be passed in, can only be read only

In this statement we have followed the same process as in the complex PIVOT example. Declared variables to hold our select list and column names, and injected them into a PIVOT statement to return a data set. 

This would return a table with the 36 dates we inserted at the start, in the example below only we only show the first 6 columns. The table would grow to however many dates were provided.

UnPivID01/01/201001/02/201001/03/201001/04/201001/05/201001/06/2010
1123456
2123456

Author

Was this helpful?

Please note, this commenting system is still in final testing.
Copyright Claytabase Ltd 2020

Registered in England and Wales 08985867

Site Links

RSSLoginLink Cookie PolicySitemap

Social Media

facebook.com/Claytabaseinstagram.com/claytabase/twitter.com/Claytabaselinkedin.com/company/claytabase-ltd

Get in Touch

+15125961417info@claytabase.comClaytabase USA, 501 Congress Avenue, Suite 150, Austin, Texas, 78701, United States

Partnered With

The settings on this site are set to allow all cookies. These can be changed on our Cookie Policy & Settings page.
By continuing to use this site you agree to the use of cookies.
Ousia Logo
Logout
Ousia CMS Loader