PIVOT/UNPIVOT SQL SERVER Examples:
CREATE TABLE Sales (State CHAR(2), SalesAmt DECIMAL(18,2))
INSERT INTO Sales VALUES ('ND',10000)INSERT INTO Sales VALUES ('SD',30000)INSERT INTO Sales VALUES ('TN',2500.50)INSERT INTO Sales VALUES ('OR',5500.50)INSERT INTO Sales VALUES ('VA',6500.50)INSERT INTO Sales VALUES ('SD',7000)INSERT INTO Sales VALUES ('ND',8000) SELECT * FROM Sales
Pivot:
SELECT [ND],[SD],[TN],[OR],[VA] FROM (SELECT State,SalesAmt FROM Sales) p PIVOT ( SUM (SalesAmt) FOR State IN ([ND],[SD],[TN],[OR],[VA]) ) AS pvt
Create the following table,
CREATE TABLE StudentMarks([Name] VARCHAR(50),Subject1 VARCHAR(10),Mark1 INT,Subject2 VARCHAR(10),Mark2 INT,Subject3 VARCHAR(10),Mark3 INT)
INSERT INTO StudentMarks([Name],Subject1,Mark1,Subject2,Mark2,Subject3,Mark3) VALUES('AAA','Science',98,'Maths',89,'English',76)
INSERT INTO StudentMarks([Name],Subject1,Mark1,Subject2,Mark2,Subject3,Mark3) VALUES('XXX','Biology',78,'Chemistry',85,'Physics',67)
INSERT INTO StudentMarks([Name],Subject1,Mark1,Subject2,Mark2) VALUES('YYY','Batany',60,'Zoology',54)
INSERT INTO StudentMarks([Name],Subject1,Mark1,Subject2,Mark2) VALUES('ZZZ','Maths',67,'Physics',78)
SELECT * FROM StudentMarks
UNPIVOT:
SELECT [Name], SubjectName, case when Subject='Subject1' then Mark1
when Subject='Subject2' then Mark2
when Subject='Subject3' then Mark3
else NULL end as Marks FROM (SELECT [Name], Subject1,Mark1, Subject2,Mark2, Subject3,Mark3
FROM StudentMarks) p UNPIVOT (SubjectName FOR Subject IN (Subject1, Subject2, Subject3) )AS unpvt;
No comments:
Post a Comment