SlideShare a Scribd company logo
1 of 8
How to use PIVOT in SQL
The PIVOT function in SQL can be used
to create a dataset with aggregated
rows from a list of data
Requirement
Assuming we have a long table of data
We want to turn this long list of dates
To this…..
A simplified summary of how many days per
month in each year
This is similar to a PIVOT table in Excel
Inner Query
Our inner query in this example is a simple list of
individual dates to make it easy to understand
But it can easily be modified to work on any
other data you want to summarise
For example
A daily list of sales transactions, which you need
to aggregate to monthly totals by year
select * from
(
select year, MonthName, date
from [dbo].[DimDate]
where year in (2018, 2019, 2020, 2021, 2022)
) a
PIVOT
(count(date)
for Monthname in
(January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December)
) b
SQL PIVOT
Here is the SQL code and a breakdown of what
each part does
This is the Inner query, which can be any
tabulated data set that you want to aggregate
This is the start of the PIVOT function, here we
have set the aggregation to be a simple count of
days per month
Here we have to specify which months we want
as column headings for the aggregations.
We do not have return every month
And we can alter the order, the columns are
returned in the order we list them
Use Cases
SQL Pivot can be very useful when you need to be able to see data over a range of columns
A good example of this any form of seasonality
Analysis of seasonality is based around having a fixed number of data points within a year so lends
itself well to using this method. It could also be used to capture sales of a product category over
weeks of the year, seeing seasonal increases and decreases over a range of years
0
5
10
15
20
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Average Daily Temperature by year
Year 1 Year 2 Year 3
Hope you found this useful
For more Tips, Tricks and
Timesavers, visit our website
Tips and Timesavers | Select Distinct Limited
Credit: Simon.harrison@select distinct limited

More Related Content

Similar to SQL Tips PIVOT Function.pptx

Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri FontainePython and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri FontaineCitus Data
 
5 ways to analyze data with pivot tables.pdf
5 ways to analyze data with pivot tables.pdf5 ways to analyze data with pivot tables.pdf
5 ways to analyze data with pivot tables.pdfKeyurBhatt1
 
Data ware dimension design
Data ware   dimension designData ware   dimension design
Data ware dimension designSayed Ahmed
 
Data ware dimension design
Data ware   dimension designData ware   dimension design
Data ware dimension designSayed Ahmed
 
Introduction to Dimesional Modelling
Introduction to Dimesional ModellingIntroduction to Dimesional Modelling
Introduction to Dimesional ModellingAshish Chandwani
 
Date dimension in your data warehouse
Date dimension in your data warehouseDate dimension in your data warehouse
Date dimension in your data warehouseDirk Cludts
 
Chris Seebacher Portfolio
Chris Seebacher PortfolioChris Seebacher Portfolio
Chris Seebacher Portfolioguest3ea163
 
Teradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional ModelsTeradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional Modelspepeborja
 
Dimensional Modeling
Dimensional ModelingDimensional Modeling
Dimensional ModelingSunita Sahu
 
08. ICV sastanak (Microsoft) Miroslav Jovković NPS 2
08. ICV sastanak (Microsoft) Miroslav Jovković NPS 208. ICV sastanak (Microsoft) Miroslav Jovković NPS 2
08. ICV sastanak (Microsoft) Miroslav Jovković NPS 2Menadžment Centar Beograd
 
Basics+of+Datawarehousing
Basics+of+DatawarehousingBasics+of+Datawarehousing
Basics+of+Datawarehousingtheextraaedge
 
Project Portfolio
Project PortfolioProject Portfolio
Project PortfolioArthur Chan
 
Time series analysis and forecasting of large cap mutual funds ..pptx
Time series analysis and forecasting of large cap mutual funds ..pptxTime series analysis and forecasting of large cap mutual funds ..pptx
Time series analysis and forecasting of large cap mutual funds ..pptxAshwinkumarBhagwat
 
ASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COM
ASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COMASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COM
ASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COMjorge0048
 

Similar to SQL Tips PIVOT Function.pptx (20)

Date Analysis .pdf
Date Analysis .pdfDate Analysis .pdf
Date Analysis .pdf
 
Group by ROLLUP in SQL Server
Group by ROLLUP in SQL ServerGroup by ROLLUP in SQL Server
Group by ROLLUP in SQL Server
 
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri FontainePython and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
Python and PostgreSQL: Let's Work Together! | PyConFr 2018 | Dimitri Fontaine
 
5 ways to analyze data with pivot tables.pdf
5 ways to analyze data with pivot tables.pdf5 ways to analyze data with pivot tables.pdf
5 ways to analyze data with pivot tables.pdf
 
Data ware dimension design
Data ware   dimension designData ware   dimension design
Data ware dimension design
 
Data ware dimension design
Data ware   dimension designData ware   dimension design
Data ware dimension design
 
Uses of excel
Uses of excelUses of excel
Uses of excel
 
Isqs6347 team5 proposal_032513
Isqs6347 team5 proposal_032513Isqs6347 team5 proposal_032513
Isqs6347 team5 proposal_032513
 
Introduction to Dimesional Modelling
Introduction to Dimesional ModellingIntroduction to Dimesional Modelling
Introduction to Dimesional Modelling
 
Star schema
Star schemaStar schema
Star schema
 
Date dimension in your data warehouse
Date dimension in your data warehouseDate dimension in your data warehouse
Date dimension in your data warehouse
 
Chris Seebacher Portfolio
Chris Seebacher PortfolioChris Seebacher Portfolio
Chris Seebacher Portfolio
 
Teradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional ModelsTeradata Aggregate Join Indices And Dimensional Models
Teradata Aggregate Join Indices And Dimensional Models
 
Dimensional Modeling
Dimensional ModelingDimensional Modeling
Dimensional Modeling
 
08. ICV sastanak (Microsoft) Miroslav Jovković NPS 2
08. ICV sastanak (Microsoft) Miroslav Jovković NPS 208. ICV sastanak (Microsoft) Miroslav Jovković NPS 2
08. ICV sastanak (Microsoft) Miroslav Jovković NPS 2
 
08. icv sastanak (microsoft) miroslav nps2
08. icv sastanak (microsoft) miroslav nps208. icv sastanak (microsoft) miroslav nps2
08. icv sastanak (microsoft) miroslav nps2
 
Basics+of+Datawarehousing
Basics+of+DatawarehousingBasics+of+Datawarehousing
Basics+of+Datawarehousing
 
Project Portfolio
Project PortfolioProject Portfolio
Project Portfolio
 
Time series analysis and forecasting of large cap mutual funds ..pptx
Time series analysis and forecasting of large cap mutual funds ..pptxTime series analysis and forecasting of large cap mutual funds ..pptx
Time series analysis and forecasting of large cap mutual funds ..pptx
 
ASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COM
ASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COMASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COM
ASSESSMENT CASE PAPER ANALYSIS / TUTORIALOUTLET DOT COM
 

More from Select Distinct Limited

Year on Year Comparison in Power BI.pptx
Year on Year Comparison in Power BI.pptxYear on Year Comparison in Power BI.pptx
Year on Year Comparison in Power BI.pptxSelect Distinct Limited
 
Sync Slicers in Power BI a step by step guide
Sync Slicers in Power BI a step by step guideSync Slicers in Power BI a step by step guide
Sync Slicers in Power BI a step by step guideSelect Distinct Limited
 
Using Google Search Console Data in Power BI.pptx
Using Google Search Console Data in Power BI.pptxUsing Google Search Console Data in Power BI.pptx
Using Google Search Console Data in Power BI.pptxSelect Distinct Limited
 
Data Lake v Data Warehouse. What is the difference?
Data Lake v Data Warehouse. What is the difference?Data Lake v Data Warehouse. What is the difference?
Data Lake v Data Warehouse. What is the difference?Select Distinct Limited
 
How to Create Drop Down Lists in Excel, step by step
How to Create Drop Down Lists in Excel, step by stepHow to Create Drop Down Lists in Excel, step by step
How to Create Drop Down Lists in Excel, step by stepSelect Distinct Limited
 
Top 5 Power BI tips 2023 most popular blog posts
Top 5 Power BI tips 2023 most popular blog postsTop 5 Power BI tips 2023 most popular blog posts
Top 5 Power BI tips 2023 most popular blog postsSelect Distinct Limited
 
Calculated Columns and Measures in Power BI.pptx
Calculated Columns and Measures in Power BI.pptxCalculated Columns and Measures in Power BI.pptx
Calculated Columns and Measures in Power BI.pptxSelect Distinct Limited
 
When to transform data for Power BI.pptx
When to transform data for Power BI.pptxWhen to transform data for Power BI.pptx
When to transform data for Power BI.pptxSelect Distinct Limited
 
Direction of travel on a map in Power BI.pptx
Direction of travel on a map in Power BI.pptxDirection of travel on a map in Power BI.pptx
Direction of travel on a map in Power BI.pptxSelect Distinct Limited
 
Power BI Connect to Google BigQuery.pptx
Power BI Connect to Google BigQuery.pptxPower BI Connect to Google BigQuery.pptx
Power BI Connect to Google BigQuery.pptxSelect Distinct Limited
 
How to use a slicer to toggle measures in Power BI
How to use a slicer to toggle measures in Power BIHow to use a slicer to toggle measures in Power BI
How to use a slicer to toggle measures in Power BISelect Distinct Limited
 

More from Select Distinct Limited (20)

Year on Year Comparison in Power BI.pptx
Year on Year Comparison in Power BI.pptxYear on Year Comparison in Power BI.pptx
Year on Year Comparison in Power BI.pptx
 
Sync Slicers in Power BI a step by step guide
Sync Slicers in Power BI a step by step guideSync Slicers in Power BI a step by step guide
Sync Slicers in Power BI a step by step guide
 
Using Google Search Console Data in Power BI.pptx
Using Google Search Console Data in Power BI.pptxUsing Google Search Console Data in Power BI.pptx
Using Google Search Console Data in Power BI.pptx
 
Data Lake v Data Warehouse. What is the difference?
Data Lake v Data Warehouse. What is the difference?Data Lake v Data Warehouse. What is the difference?
Data Lake v Data Warehouse. What is the difference?
 
How to Create Drop Down Lists in Excel, step by step
How to Create Drop Down Lists in Excel, step by stepHow to Create Drop Down Lists in Excel, step by step
How to Create Drop Down Lists in Excel, step by step
 
Top 5 Power BI tips 2023 most popular blog posts
Top 5 Power BI tips 2023 most popular blog postsTop 5 Power BI tips 2023 most popular blog posts
Top 5 Power BI tips 2023 most popular blog posts
 
CTEs in SQL.pptx
CTEs in SQL.pptxCTEs in SQL.pptx
CTEs in SQL.pptx
 
Calculated Columns and Measures in Power BI.pptx
Calculated Columns and Measures in Power BI.pptxCalculated Columns and Measures in Power BI.pptx
Calculated Columns and Measures in Power BI.pptx
 
Divide by Zero Errors
Divide by Zero ErrorsDivide by Zero Errors
Divide by Zero Errors
 
When to transform data for Power BI.pptx
When to transform data for Power BI.pptxWhen to transform data for Power BI.pptx
When to transform data for Power BI.pptx
 
Power BI KPIs
Power BI KPIsPower BI KPIs
Power BI KPIs
 
Direction of travel on a map in Power BI.pptx
Direction of travel on a map in Power BI.pptxDirection of travel on a map in Power BI.pptx
Direction of travel on a map in Power BI.pptx
 
UNION in DAX
UNION in DAXUNION in DAX
UNION in DAX
 
APPEND data in Power Query
APPEND data in Power QueryAPPEND data in Power Query
APPEND data in Power Query
 
Power BI Connect to Google BigQuery.pptx
Power BI Connect to Google BigQuery.pptxPower BI Connect to Google BigQuery.pptx
Power BI Connect to Google BigQuery.pptx
 
Advanced Top N Measures in Power BI
Advanced Top N Measures in Power BIAdvanced Top N Measures in Power BI
Advanced Top N Measures in Power BI
 
Custom Formats in Power BI
Custom Formats in Power BICustom Formats in Power BI
Custom Formats in Power BI
 
Power BI Tips Top N Measures.pptx
Power BI Tips Top N Measures.pptxPower BI Tips Top N Measures.pptx
Power BI Tips Top N Measures.pptx
 
Power BI Drill Through
Power BI Drill ThroughPower BI Drill Through
Power BI Drill Through
 
How to use a slicer to toggle measures in Power BI
How to use a slicer to toggle measures in Power BIHow to use a slicer to toggle measures in Power BI
How to use a slicer to toggle measures in Power BI
 

Recently uploaded

PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
Spark3's new memory model/management
Spark3's new memory model/managementSpark3's new memory model/management
Spark3's new memory model/managementakshesh doshi
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystSamantha Rae Coolbeth
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxFurkanTasci3
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfgstagge
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Servicejennyeacort
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfLars Albertsson
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 

Recently uploaded (20)

PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
Spark3's new memory model/management
Spark3's new memory model/managementSpark3's new memory model/management
Spark3's new memory model/management
 
Unveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data AnalystUnveiling Insights: The Role of a Data Analyst
Unveiling Insights: The Role of a Data Analyst
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptx
 
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls CP 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdf
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts ServiceCall Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
Call Girls In Noida City Center Metro 24/7✡️9711147426✡️ Escorts Service
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
Industrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdfIndustrialised data - the key to AI success.pdf
Industrialised data - the key to AI success.pdf
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 

SQL Tips PIVOT Function.pptx

  • 1. How to use PIVOT in SQL
  • 2. The PIVOT function in SQL can be used to create a dataset with aggregated rows from a list of data
  • 3. Requirement Assuming we have a long table of data We want to turn this long list of dates To this….. A simplified summary of how many days per month in each year This is similar to a PIVOT table in Excel
  • 4. Inner Query Our inner query in this example is a simple list of individual dates to make it easy to understand But it can easily be modified to work on any other data you want to summarise For example A daily list of sales transactions, which you need to aggregate to monthly totals by year
  • 5. select * from ( select year, MonthName, date from [dbo].[DimDate] where year in (2018, 2019, 2020, 2021, 2022) ) a PIVOT (count(date) for Monthname in (January, February, March, April, May, June, July, August, September, October, November, December) ) b SQL PIVOT Here is the SQL code and a breakdown of what each part does This is the Inner query, which can be any tabulated data set that you want to aggregate This is the start of the PIVOT function, here we have set the aggregation to be a simple count of days per month Here we have to specify which months we want as column headings for the aggregations. We do not have return every month And we can alter the order, the columns are returned in the order we list them
  • 6. Use Cases SQL Pivot can be very useful when you need to be able to see data over a range of columns A good example of this any form of seasonality Analysis of seasonality is based around having a fixed number of data points within a year so lends itself well to using this method. It could also be used to capture sales of a product category over weeks of the year, seeing seasonal increases and decreases over a range of years 0 5 10 15 20 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Average Daily Temperature by year Year 1 Year 2 Year 3
  • 7. Hope you found this useful
  • 8. For more Tips, Tricks and Timesavers, visit our website Tips and Timesavers | Select Distinct Limited Credit: Simon.harrison@select distinct limited