tags:

views:

22

answers:

2

Hello

I was hoping someone could help me with this

I have data like this :

SERVICE ITEM1    ITEM2    ITEM3    ITEM4  
GOLD    0        0        0        0
SILVER  2      2       0        2  
BRONZE  0      4       0        26  

But want it like this:

GOLD  SILVER    BRONZE
2  0        0
2  0        4
0  0        0
2  0        26

I think this is an unpivot, but cant figure out the syntax

many thanks

A: 

Get familiar with PIVOT

Vash
thanka, I am familiar, but I beleive this is an unpivot that I need
lee
the problem I am having is getting a seperate column for gold, silver and ,bronze. I think this requires multiple unpivots but cannot figure out the syntax
lee
If i find some time i will try to help.
Vash
+2  A: 
/*Create testing Data - You don't need this*/
SELECT * 
INTO #YourTable FROM 
(
SELECT 'GOLD' AS SERVICE, 0 AS ITEM1, 0 AS ITEM2, 0 AS ITEM3, 0 AS ITEM4 UNION ALL 
SELECT 'SILVER' AS SERVICE, 2 AS ITEM1, 2 AS ITEM2, 0 AS ITEM3, 2 AS ITEM4 UNION ALL 
SELECT 'BRONZE' AS SERVICE, 0 AS ITEM1, 4 AS ITEM2, 0 AS ITEM3, 26 AS ITEM4
) testdata


/*You just need this*/    
SELECT * 
FROM 
    /*Substitute the name of your table here*/
    (SELECT SERVICE, ITEM1, ITEM2, ITEM3, ITEM4 FROM #YourTable) BaseData
UNPIVOT
   (Vals FOR Item IN 
      (ITEM1, ITEM2, ITEM3, ITEM4)
 )AS unpvt
 PIVOT (SUM(Vals) FOR SERVICE IN ([GOLD],[SILVER],[BRONZE]) ) AS pvt;
Martin Smith
thanks Martin, but the values (i.e. bronze 0,4,0,26) are variable. This is a view of a view so the values will change
lee
You mean that the columns `GOLD`,`SILVER`,`BRONZE` aren't fixed? If so you'll need dynamic SQL.
Martin Smith
sorry, yes the columns are fixed, but the numbers will change value
lee
Well it should work for you then. Just delete the `;With T AS (...)` bit and change `SELECT * FROM T` to `SELECT SERVICE, ITEM1, ITEM2, ITEM3, ITEM4 FROM YourTable`
Martin Smith
thanks buddy, much appreciated
lee
im confused :S so basically do a union between 3 selects (each with a where clause to specifiy the metallic) then pivot off of that?
lee
@lee - No See edit.
Martin Smith
thank you thank you thank you !!! ive spent all day on this f'ing think and it works now :DDD
lee