I'm trying to understand the PIVOT
and UNPIVOT
commands in T-SQL on SQL Server 2012. I completely understand what these commands do, but I want to understand a few more details.
Currently I lack in understanding in why when I try to use unpivot I must put the original names of columns of the source table for the pivot command. First I've created a new table and put some data there from another one using pivot command.
USE testdb;
IF OBJECT_ID('dbo.EmpCustOrders', 'U') IS NOT NULL
DROP TABLE dbo.EmpCustOrders;
SELECT empid, A, B,C, D
INTO dbo.EmpCustOrders
FROM (SELECT empid, custid, qty
FROM dbo.Orders) AS D
PIVOT (SUM(qty) FOR custid IN (A, B, C, D)) As newtable;
All ok. Then I try to use UNPIVOT
command for just creating some table view:
USE testdb;
SELECT empid, custid, qty
FROM dbo.EmpCustOrders
UNPIVOT (qty FOR custid IN (A, B, C, D)) AS newTable;
Result - this all works perfectly, I can understand why, when I write SELECT
, I must put names of columns as custid
and qty
that are exactly the same as they are in the previous table, but not when I'm writing the UNPIVOT
on the seperate derived table. How and where is this information stored in the just created table? What part of this am I missing...
For better illustartation of question - add some pic with described situation.
EDIT
You don't need to use the same column names but what you are doing is reversing the previous command, in this case the original field names make sense.
USE testdb;
SELECT empid, apples, oranges
FROM dbo.EmpCustOrders
UNPIVOT (oranges FOR apples IN (A, B, C, D)) AS newTable;
Would work equally as well, but make less sense.