2009-06-02 81 views
1

我有以下結果集:SQL樞軸上子集

類型|方法|量

的Type1現金數額
類型1,取適量
2型現金數額
類型2,取適量
的Type3現金數額
的Type3支票金額


我想使它看起來像這樣:

類型|現金|檢查

的Type1金額金額
2型金額金額
的Type3金額金額

我怎樣才能在T-SQL(2005語法即可)實現這一目標?我需要通過類型轉動(1,2,3 ...)

回答

0

這裏是在PIVOT嘗試:

select * 
from YourTable 
PIVOT (sum(amount) FOR Method in (Cash,Check)) as Y 

鑑於這只是兩列,可以與嘗試加入:

select 
    type 
, cash = a.amount 
, check = b.amount 
from yourtable a 
full join yourtable b on a.type = b.type 
where a.method = 'cash' or b.method = 'Check' 
+0

謝謝。還有其他欄目 - 這只是一個例子。 – 2009-06-02 07:30:47

0

或者更好的是:

select 
    Type 
, Cash = sum(case when Method = 'Cash' then Amount end) 
, Check = sum(case when Method = 'Check' then Amount end) 
from yourtable 
group by 
    Type 

添加ELSE 0到合適的話CASE語句。

該表格比PIVOT操作員更靈活,不需要完全連接。只是直接聚合。