2012-10-17 61 views
0

以下是我的查詢逆透視T-SQL查詢

Year_Month.........cat1_per......cat2_per........cat3_per......cat4_per 
2004_06...............0.892..........0.778............0.467..........0.871 
2005_10...............0.790..........0.629............0.581..........0.978 

的結果,但我想我的查詢的輸出是

Category...........2004_06..............2005_10 
cat1_per.............0.892..................0.790 
cat2_per.............0.778..................0.629 
cat3_per.............0.467..................0.581 
cat4_per.............0.871..................0.978 

是什麼做的最好方法是什麼?任何幫助表示讚賞。 我試過Unpivot但無法獲得想要的結果。

+0

您使用的是哪種rdbms? – Taryn

回答

2

你沒有指定RDBMS,但自你標記它我猜sql-server。這其實是一個UNPIVOT,然後是一個PIVOT。如果你知道你需要改變的值,那麼你可以通過一個靜態版本硬編碼它們:

select * 
from 
(
    select year_month, value, category 
    from table1 
    unpivot 
    (
    value 
    for category in (cat1_per, cat2_per, cat3_per, cat4_per) 
) un 
) x 
pivot 
(
    max(value) 
    for year_month in ([2004_06], [2005_10]) 
)p 

SQL Fiddle With Demo

如果再有一個未知數量的值進行改造,那麼你可以使用動態SQL樞軸:

DECLARE @colsUnpivot AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX), 
    @colsPivot as NVARCHAR(MAX) 

select @colsUnpivot = stuff((select ','+quotename(C.name) 
     from sys.columns as C 
     where C.object_id = object_id('Table1') and 
       C.name like 'cat%per' 
     for xml path('')), 1, 1, '') 

select @colsPivot = STUFF((SELECT ',' 
         + quotename(t.year_month) 
        from Table1 t 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 


set @query 
    = 'select * 
     from 
     (
     select year_month, value, category 
     from table1 
     unpivot 
     (
      value 
      for category in ('+ @colsunpivot +') 
     ) un 
    ) x 
     pivot 
     (
     max(value) 
     for year_month in ('+ @colspivot +') 
    ) p' 

exec(@query) 

參見SQL Fiddle with demo

兩者都將產生相同的結果:

select category, 
    max(case when year_month = '2004_06' then value end) [2004_06], 
    max(case when year_month = '2005_10' then value end) [2005_10] 
from 
(
    select year_month, cat1_per value, 'cat1_per' category 
    from table1 
    union all 
    select year_month, cat2_per value, 'cat2_per' category 
    from table1 
    union all 
    select year_month, cat3_per value, 'cat3_per' category 
    from table1 
    union all 
    select year_month, cat4_per value, 'cat4_per' category 
    from table1 
) un 
group by category 
| CATEGORY | 2004_06 | 2005_10 | 
-------------------------------- 
| cat1_per | 0.892 | 0.79 | 
| cat2_per | 0.778 | 0.629 | 
| cat3_per | 0.467 | 0.581 | 
| cat4_per | 0.871 | 0.978 | 

如果由於某種原因,你沒有足夠的UNPIVOTPIVOT功能,那麼你可以在此使用的UNION ALL組合來UNPIVOT然後CASE聲明和集合函數來透視複製

請參閱SQL Fiddle with Demo

+0

感謝您的Swift響應。當我使用第一個查詢時出現以下錯誤 Msg 156,Level 15,State 1,Line 30 關鍵字'FOR'附近的語法錯誤。 –

+0

@arvindreddy您正在使用的查詢是什麼?它似乎在我的小提琴演示 - http://sqlfiddle.com/#!3/c93d6/8 – Taryn

+0

@arvindreddy很高興你的工作。如果StackOverflow上的任何答案都有幫助,請務必通過左側的複選標記對其進行上傳和/或標記爲已接受。它有助於未來的遊客,甚至增加你的代表。 :) – Taryn