I am facing the following challenge. I need to rotate table data twice over the same column. Here's a screenshot of the data.
I want to have one row for each Item ID containing both the purchasing value and the selling value for each year. I tried doing this by selecting the "year" column twice, formatting it a bit so each selling year gets prefixed with a "S" and each purchasing year begins with a "P", and using 2 pivots to rotate around the 2 year columns. Here's the SQL query (used in SQL Server 2008):
SELECT [Item ID],
[P2000],[P2001],[P2002],[P2003],
[S2000],[S2001],[S2002],[S2003]
FROM
(
SELECT [Item ID]
,'P' + [Year] AS YearOfPurchase
,'S' + [Year] AS YearOfSelling
,[Purchasing value]
,[Selling value]
FROM [ItemPrices]
) AS ALIAS
PIVOT
(
MIN ([Purchasing value]) FOR [YearOfPurchase] in ([P2000],[P2001],[P2002],[P2003])
)
AS pvt
PIVOT
(
MIN ([Selling value]) FOR [YearOfSelling] in ([S2000],[S2001],[S2002],[S2003])
)
AS pvt2
The result is not exactly what I was hoping for (see image below):
As you can see, there are still more than one row for each item ID. Is there a way to reduce the number of rows to exactly one per item? So that it looks a bit like the Excel screenshot below?
4条答案
按热度按时间wn9m85ua1#
My suggestion would be to apply both the
UNPIVOT
and thePIVOT
functions to get the result.The
UNPIVOT
will turn thePurchasingValue
andSellingValue
columns into rows. Once this is done, then you can pivot the data into your result.The code will be:
See SQL Fiddle with Demo. The result is:
In SQL Server 2008+ you can use
CROSS APPLY
withVALUES
along with thePIVOT
function:See SQL Fiddle with Demo
ioekq8ef2#
One easy way to pivot multiple columns is to just use Aggregate(Case) expressions.
pprl5pva3#
Use a GROUP BY ItemID, with aggregate function SUM(isnull(value,0)) on each of the results columns.
s4chpxco4#
I achieved something similar by pivoting the already pivoted dataset (essentially pivoting twice), then grouping by the necessary attributes to get the results Im after. Still executes in a couple of seconds with thousands of rows.' Using the example in the question, the pivoting twice is correct, there just needs to be a summing of the buy and sell values and a group by at the end of the statement.