Introduction:
Today I am going to show you how to use the Pivot Table in Sql.
This Pivot table is mainly used for the converting the row into column and then you can apply the aggregate function in the pivot table.
Lets see the Example.
First lets create the table and insert the data into the table.
CREATE TABLE tblPivot
(
colA nvarchar(500),
colB nvarchar(500),
colC int
)
INSERT INTO tblPivot VALUES('A', 'X', 1)
INSERT INTO tblPivot VALUES('A', 'Y', 2)
INSERT INTO tblPivot VALUES('A', 'Z', 3)
INSERT INTO tblPivot VALUES('A', 'X', 4)
INSERT INTO tblPivot VALUES('A', 'Y', 5)
INSERT INTO tblPivot VALUES('B', 'Z', 6)
INSERT INTO tblPivot VALUES('B', 'X', 7)
INSERT INTO tblPivot VALUES('B', 'Y', 8)
INSERT INTO tblPivot VALUES('B', 'Z', 9)
INSERT INTO tblPivot VALUES('C', 'X', 10)
INSERT INTO tblPivot VALUES('C', 'Y', 11)
INSERT INTO tblPivot VALUES('C', 'Z', 12)
select * from tblPivot
Now lets apply the Pivot Querry.
DECLARE @columns nvarchar(max)
SELECT
@columns =
STUFF
(
(
SELECT DISTINCT
', [' + colB + ']'
FROM
tblPivot
FOR XML PATH('')
), 1, 1, ''
)
EXEC
('
SELECT
*
FROM
(
SELECT
colA,
colB,
colC
FROM
tblPivot
) DATA
PIVOT
(
SUM(DATA.colC)
FOR
colB
IN
(
' + @columns + '
)
) PVT
')
and then see the Output
colA X Y Z
A 5 7 3
B 7 8 15
C 10 11 12
If you close Look at the above querry then you can see the I convert the colB data values into Column and then i just apply the sum of it.
Today I am going to show you how to use the Pivot Table in Sql.
This Pivot table is mainly used for the converting the row into column and then you can apply the aggregate function in the pivot table.
Lets see the Example.
First lets create the table and insert the data into the table.
CREATE TABLE tblPivot
(
colA nvarchar(500),
colB nvarchar(500),
colC int
)
INSERT INTO tblPivot VALUES('A', 'X', 1)
INSERT INTO tblPivot VALUES('A', 'Y', 2)
INSERT INTO tblPivot VALUES('A', 'Z', 3)
INSERT INTO tblPivot VALUES('A', 'X', 4)
INSERT INTO tblPivot VALUES('A', 'Y', 5)
INSERT INTO tblPivot VALUES('B', 'Z', 6)
INSERT INTO tblPivot VALUES('B', 'X', 7)
INSERT INTO tblPivot VALUES('B', 'Y', 8)
INSERT INTO tblPivot VALUES('B', 'Z', 9)
INSERT INTO tblPivot VALUES('C', 'X', 10)
INSERT INTO tblPivot VALUES('C', 'Y', 11)
INSERT INTO tblPivot VALUES('C', 'Z', 12)
select * from tblPivot
Now lets apply the Pivot Querry.
DECLARE @columns nvarchar(max)
SELECT
@columns =
STUFF
(
(
SELECT DISTINCT
', [' + colB + ']'
FROM
tblPivot
FOR XML PATH('')
), 1, 1, ''
)
EXEC
('
SELECT
*
FROM
(
SELECT
colA,
colB,
colC
FROM
tblPivot
) DATA
PIVOT
(
SUM(DATA.colC)
FOR
colB
IN
(
' + @columns + '
)
) PVT
')
and then see the Output
colA X Y Z
A 5 7 3
B 7 8 15
C 10 11 12
If you close Look at the above querry then you can see the I convert the colB data values into Column and then i just apply the sum of it.
0 comments:
Post a Comment