What is PIVOT in SQL ?
Pivot is a SQL server operator that can transform unique values from one column in a result-set into multiple columns in the output , hence it seems like rotating the table OR simply we can remembered that PIVOT is very useful technique to transform or display data Row level to Column.
Example
Suppose we have a Population table of the multiple countries of 2019, the population count did in several months of the year. We want the output that Population count of country month wise.
We have a population table with below information.
CREATE TABLE [dbo].[T_Population](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Country] [varchar](50) NULL,
[PopulationCountDate] [date] NULL,
[PopulationCount] [int] NULL,
CONSTRAINT [PK_T_Population] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SELECT *
FROM (
SELECT Country,
left(datename(month,PopulationCountDate),3)as [month], PopulationCount
FROM T_Population
) as s
PIVOT
(
SUM(PopulationCount) FOR [month] IN (JAN, FEB, MAR, APR,MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC)
)AS pvt
The Output Should like this. |
Summary
Post a Comment