How to use simple PIVOT in SQL server(Static
Columns)
PIVOT: - Pivot is the
concept of converting the rows to the columns & columns to the rows
This is the static
columns display (User manually write the columns names )
Declare
@SampleTable as table (Sno int,Names nvarchar(50),Subjects nvarchar(50),
Marks int,Location nvarchar(50));
insert
into @SampleTable VALUES(1,'Lokesh','Maths',95,'Hyderabad');
insert
into @SampleTable VALUES(2,'Lokesh','Science',25,'Hyderabad');
insert
into @SampleTable VALUES(3,'Krishna','Maths',59,'Chennai');
insert
into @SampleTable VALUES(4,'Krishna','Science',56,'Chennai');
insert
into @SampleTable VALUES(5,'Google','Maths',25,'UnNone');
insert
into @SampleTable VALUES(6,'Google','Science',80,'UnNone');
--This is the Existing Table Result
SELECT
* FROM
@SampleTable;
with
CTE
as
(
SELECT * from @SampleTable
PIVOT
(
SUM(Marks) FOR Subjects IN ([Maths],Science)
) as pivottable
)
--This is PIVOT table result
SELECT Names,Location,SUM(Maths) Maths,SUM(Science)Science from CTE group by Names,Location
No comments:
Post a Comment