2014-03-04 28 views
0

請參閱表的SQL Server:談到某些行成列在下面

對於每一個客戶ID + PaymentID + ClaimNum,還有對項目ID &數量3個NULL值。

我想取這3個NULL值並將它們作爲COLUMNS。

DeductionID 1085 =服務費用(列名稱)

DeductionID 486 =貨運費(列名稱)

DeductionID 559 =手續費(列名稱)

例如,讓我們採取ClaimNum突出顯示的空值:

做我想做的事,它最終會與下面的列:

CustomerID,PaymentID,ClaimNum,ItemID,數量,金額,服務費,運費,手續費

我不知道是否需要在這裏做CROSS JOIN,PIVOT或UNPIVOT。過去我從來沒有這樣做過,在這方面閱讀微軟的網站並沒有什麼幫助。任何人都可以幫我一把嗎?

讓我知道你是否需要更多信息。我感謝所有的幫助!!

+0

你能告訴我們你想要的結果的例子嗎? – Andrew

+0

是的,掛在... –

回答

1

您可以透視,然後回到原始數據。

即:

select 
    yourtable.* , Service, handling, freight 
from yourtable 
    inner join 
(
    select CustomerID, PaymentID, ClaimNum, 
      [1085] as Service, [486] as freight, [559] as handling 
    from 
      (select customerid, paymentid, claimnum, DeductionID, Amount from yourtable) t 
       pivot 
     (sum (amount) for DeductionID in ([1085],[486],[559]))p 
     ) pt 
    on yourtable.CustomerID = pt.CustomerID 
    and yourtable.PaymentID = pt.PaymentID 
    and yourtable.ClaimNum = pt.ClaimNum 
where ItemID is not null 
+0

謝謝你,這個伎倆。 –