2012-04-23 78 views
1

我有一個查詢週期和三列,這是不同的數據類型。Unpivot多列和值

abc: int 
def: decimal 
hij: int 

這三列的數據來自不同的查詢。

這是當前結果

Period abc def hij 
------ ---- ---- --- 
2012-01 10 0.00 4 
2012-02  5 0.00 5 
2012-03  0 2.40 8 

我想獲得以下輸出

abc 2012-01 10 0.00 
abc 2012-02 5 0.00 
abc 2012-03 0 0.00 
def 2012-01 0 0.00 
def 2012-02 0 0.00 
def 2012-03 0 2.40 
hij 2012-01 4 0.00 
hij 2012-02 5 0.00 
hij 2012-03 8 0.00 

我想用unpivot的,但它給我的錯誤衝突類型。

+0

你能提供用於生產當前結果查詢,使它更容易回答你的問題? – erikxiv 2012-04-23 19:17:26

+0

看看這個[回答](http://stackoverflow.com/questions/10266494/how-to-change-the-information-in-this-table-into-an-easy-to-use-form/10266894# 10266894)。 – 2012-04-23 21:45:58

回答

4

你得到的錯誤是因爲你在UNPIVOT中混合了decimal和int。

它看起來像你想UNPIVOT,但然後單獨def再次從其他列退出。

我能達到什麼樣的似乎是這樣期望的結果:

declare @t table(Period varchar(10), abc int, def decimal(5,2), hij int) 
insert into @t values ('2012-01',10,0.00,4) 
, ('2012-02',5,0.00,5) 
, ('2012-03',0,2.40,8); 

with a as (
    select cols, Period, val 
    from (select Period, abc=CAST(abc as decimal(5,2)), def, hij=CAST(hij as decimal(5,2)) from @t) p 
    UNPIVOT (
     val for cols in (abc, def, hij) 
    ) as unpvt 
) 
select a.cols 
, Period 
, abc_hij=case when cols in ('abc','hij') then CAST(val as int) else 0 end 
, def=case when cols = ('def') then val else 0.00 end 
from a 
order by cols, Period 
go 

結果:

enter image description here

+0

我喜歡這個,非常感謝你 – berhiamt68 2012-04-24 14:08:23

+0

不客氣。如果這對您有用,請通過解決方案檢查已接受的複選框:) – 2012-04-24 14:12:17

0
 
WITH c AS (
SELECT '2012-01' AS Period, 10 AS abc , 0.00 AS def, 4 AS hij 
UNION ALL 
SELECT '2012-02' AS Period,  5 AS abc, 0.00 AS def , 5 AS hij 
UNION ALL 
SELECT '2012-03' AS Period,  0 AS abc, 2.40 AS def, 8 AS hij 
) 
SELECT * FROM (
SELECT cc.title, c.Period,cc.val FROM c 
cross apply 
(
    VALUES('abc',abc),('def',def),('hij',hij) 
) cc (title,val) 
) t 
ORDER BY t.title