Hi friends
I want to know what is PIVOT and UNPIVOT in SQL Server.
Thank you.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Vinitha TPosted Nov 18, 2021, 12:09 PM
Satyapriya NayakPosted Jun 12, 2012, 9:10 AM
You can use the PIVOT and UNPIVOT relational operators to manipulate a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where necessary on any remaining column values that are desired in the final output. UNPIVOT performs the opposite operation to PIVOT by rotating columns of a table-valued expression into column values. Every PIVOT query involves an aggregation of some type.
There are two ways to pivot data:
Use the following scripts,
Insert values,
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 SalesHere is the result set,
Run the following query,
Here is the result set,
UNPIVOT performs almost the reverse operation of PIVOT, by rotating columns into rows.
Use the following scripts,
Insert values,
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 StudentMarksHere is the result set,
Run the following query,
Here is the result set,
Note that UNPIVOT is not the exact reverse of PIVOT. PIVOT performs an aggregation and hence merges possible multiple rows into a single row in the output. UNPIVOT does not reproduce the original table-valued expression result because rows have been merged. Besides, NULL values in the input of UNPIVOT disappear in the output, whereas there may have been original NULL values in the input before the PIVOT operation.
Please refer the below links
http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
http://www.sql-programmers.com/using-pivot-and-unpivot.aspx
Thanks
Posted Jun 12, 2012, 9:06 AM
http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/