Do you want to learn how to unpivot a table in SQL Server?
Unpivot is a handy operator that converts columns into rows, making your data more normalized and readable.
Check out my latest blog post to see how it works and why you should use it.
https://www.selectdistinct.co.uk/2023/06/12/unpivot-function-in-sql/
#sql #unpivot #datatransformation #sqlserver #blogpost
2. The UNPIVOT function in SQL is used to
transform a dataset from columns to
rows
(Into a normalized table)
3. From This…
A wide table of columns
Such as this….
To this…..
A table of Year, Month and days per month
4. Data Set Up
If you want to follow this example, you can run the following SQL to create the dataset used in this example
CREATE TABLE [dbo].[UNPIVOT_Example](
[year] [int] NULL,
[January] [int] NULL,
[February] [int] NULL,
[March] [int] NULL,
[April] [int] NULL,
[May] [int] NULL,
[June] [int] NULL,
[July] [int] NULL,
[August] [int] NULL,
[September] [int] NULL,
[October] [int] NULL,
[November] [int] NULL,
[December] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[UNPIVOT_Example] ([year], [January], [February], [March], [April], [May], [June], [July],
[August], [September], [October], [November], [December])
VALUES
(2018, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(2019, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(2020, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(2021, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(2022, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
GO
5. select Year, Month, days
from [dbo].[UNPIVOT_Example]
UNPIVOT
(days
for Month in
([January]
, [February]
, [March]
, [April]
, [May]
, [June]
, [July]
, [August]
, [September]
, [October]
, [November]
, [December])
)as dpm_unpivot
SQL UNPIVOT
Here is the SQL code and a breakdown of what
each part does
3. This is the final set of columns that we want to
output
2. This is the start of the UNPIVOT function,
We define the column ‘MONTH’ using the full
list of existing column names
‘days’ is the new name for the column of data
that we will generate from the UNPIVOT
1. Here we select each
of the columns of data
that we want to be
unpivoted
6. Use Cases
SQL UNPIVOT is very useful when the data you have to work with is already in a PIVOTED style
Quite often we come across that is provided to us in this way, usually as outputs from proprietary
systems
Converting these to tabular data sets makes working with the data much easier, and allows far
simpler work if you need to aggregate all the data by year
7. UNPIVOT is a powerful and useful operator that can help you transform
your data in SQL Server.
You can use it to normalize your tables, or to reverse the effect of a PIVOT
operation.
You can also combine it with other operators and functions to perform
more complex transformations.
8. For more Tips, Tricks and
Timesavers, visit our website
Business Analytics Blog – Select Distinct
Credit: simon.harrison@selectdistinct.co.uk