How to use the PIVOT function in SQL Server
PIVOT is used in a similar way to a pivot table in Excel, to create aggregated columns from a long dataset
This short guide shows how it works and what it can be used for
#SQL #pivot #SQLPIVOT
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