I’m trying to make a PIVOT-query out of a working table with the structure:
DECLARE @workingData TABLE
(
location VARCHAR(20),
name VARCHAR(50),
sales_type VARCHAR(20),
local_id VARCHAR(15),
house_description VARCHAR(40),
sales_order VARCHAR(10),
order_year INT,
amount NUMERIC(14,0)
)
The name column contains one of two values: ‘name1’ or ‘name2’. These must be used in the grouping as described below.
I’d like it to become a table with the columns:
location
sales_type
local_id
house_description
sales_order
name1_2007
name2_2007
name1_2008
name2_2008
name1_2009
name2_2009
name1_2010
name2_2010
I tried this:
SELECT
location, sales_type, local_id, house_description, sales_order,
MAX([1]) AS [name1_2007], MAX([2]) AS [name2_2007],
MAX([3]) AS [name1_2008], MAX([4]) AS [name2_2008],
MAX([5]) AS [name1_2009], MAX([6]) AS [name2_2009],
MAX([7]) AS [name1_2010], MAX([8]) AS [name2_2010],
'2010' As [Base Year]
FROM (
SELECT location, sales_type, local_id, house_description, sales_order, order_year, name, amount
,ROW_NUMBER() OVER ( PARTITION BY location, sales_type, local_id, sales_order
ORDER BY order_year, name) AS seq
FROM @workingData
) AS SourceTable
PIVOT
(
MAX(amount)
FOR seq IN ([1], [2], [3], [4], [5], [6], [7], [8], [9])
) AS PivotTable
GROUP BY
location, sales_type, local_id, house_description, sales_order
And this ALMOST works! 😉 But my values are not placed in the correct columns. If a particular value exists for a certain location, sales_type, local_id, house_description and sales_order it is always outputted in the [1] column. But this should be determined on wether it is name1 or name2 and its order_year!
I understand that what I see is a direct result of my row_number operation, that calculates the seq-column to be 1 if only one entry exists. So maybe I’m attacking this the wrong way?
Can anybody solve this?
Although you only have Name1 and Name2 ATM, this is a typical example of a dynamic pivot.
Create the following SP:
Now things become easier. From the input
we aggregate by name and year
giving
then, using the pivot_sp
we obtain
HTH