CREATE A TABLE CALLED CAR
CREATE TABLE CAR(ID INT,NAME NVARCHAR(20),COLOR NVARCHAR(20));
INSERT INTO CAR
SELECT 1,'TATA SUMO','RED' UNION
SELECT 2,'TATA SUMO','BLUE' UNION
SELECT 3,'TATA SUMO','WHITE' UNION
SELECT 4,'TATA SUMO','SILVER' UNION
SELECT 6,'MARUTHI','BLUE' UNION
SELECT 7,'MARUTHI','WHITE' UNION
SELECT 5,'MARUTHI','RED' UNION
SELECT 8,'MARUTHI','SILVER' UNION
SELECT 9,'SAFARI','WHITE' UNION
SELECT 10,'SAFARI','SILVER' UNION
SELECT 11,'TATA SUMO','RED' UNION
SELECT 12,'TATA SUMO','SILVER'
SELECT * FROM CAR
SELECT * FROM (SELECT * FROM CAR) p
PIVOT (count(ID) FOR COLOR IN (RED,BLUE,WHITE,SILVER)) AS pvt
Order by NAME DESC
SELECT * FROM (SELECT * FROM CAR) p
PIVOT (count(ID) FOR NAME IN ("TATA SUMO",SAFARI,MARUTHI)) AS pvt
O/P:
TAGS: Switching rows as columns in sqlserver, using pivot in sql server, sql pivot
CREATE TABLE CAR(ID INT,NAME NVARCHAR(20),COLOR NVARCHAR(20));
INSERT INTO CAR
SELECT 1,'TATA SUMO','RED' UNION
SELECT 2,'TATA SUMO','BLUE' UNION
SELECT 3,'TATA SUMO','WHITE' UNION
SELECT 4,'TATA SUMO','SILVER' UNION
SELECT 6,'MARUTHI','BLUE' UNION
SELECT 7,'MARUTHI','WHITE' UNION
SELECT 5,'MARUTHI','RED' UNION
SELECT 8,'MARUTHI','SILVER' UNION
SELECT 9,'SAFARI','WHITE' UNION
SELECT 10,'SAFARI','SILVER' UNION
SELECT 11,'TATA SUMO','RED' UNION
SELECT 12,'TATA SUMO','SILVER'
SELECT * FROM CAR
SELECT * FROM (SELECT * FROM CAR) p
PIVOT (count(ID) FOR COLOR IN (RED,BLUE,WHITE,SILVER)) AS pvt
Order by NAME DESC
SELECT * FROM (SELECT * FROM CAR) p
PIVOT (count(ID) FOR NAME IN ("TATA SUMO",SAFARI,MARUTHI)) AS pvt
O/P:
TAGS: Switching rows as columns in sqlserver, using pivot in sql server, sql pivot
No comments:
Post a Comment