2014-09-04 160 views
0

我正在嘗試編寫一個查詢,其中我加入的一個表可能包含每個唯一ID的多行。我想在結果中組合這些行,以便每個唯一的ID只有一行。將多行組合成一行並將其分隔列

請參考下面的簡單例子:

Tender表:

ID  | TenderType | TenderAmount 
---------------------------------------- 
4567 | Cash   | 40.00 
4568 | Cash   | 22.00 
4568 | Visa   | 86.00 
4568 | Gift Card  | 10.00 
4570 | Cash   | 66.00 
4570 | MC   | 30.00 

期望的結果:

ID | TenderType1 | TenderType2 | TenderType3 | TenderAmount1 | TenderAmount2 | TenderAmount3 | 
------------------------------------------------------------------------------------------------ 
4567 | Cash  |    |    | 40.00   |    |    | 
4568 | Cash  | Visa  | Gift Card | 22.00   | 86.00   | 10.00   | 
4570 | Cash  | MC   |    | 66.00   | 30.00   |    | 

我使用SQL Server 2005的任何幫助將是驚人的。

+0

我很喜歡這句話:「我參加可以包含每種唯一的ID多行的表中的一個」。如果它們重複,則ID不是*唯一*。 (雖然我知道你的意思。) – 2014-09-04 15:05:31

+0

哈!我明白這可能會被誤讀。在原始表格中,這個值不是唯一的,但是在我的查詢中它會(希望)成爲。 – 2014-09-04 15:08:32

回答

0

這是'數據透視'。你應該看看如何做數據透視表。

0
;WITH CashCTE AS 
(
    SELECT ID, 
      TenderType, 
      TenderAmount 
    FROM Tender 
    WHERE TenderType = 'Cash' 
),GiftCardCTE AS 
(
    SELECT ID, 
      TenderType, 
      TenderAmount 
    FROM Tender 
    WHERE TenderType = 'Gift Card' 
),CreditCardCTE AS 
(
    SELECT ID, 
      TenderType, 
      TenderAmount 
    FROM Tender 
    WHERE TenderType IN ('Visa','MC') 
) 

SELECT COALESCE(C.ID,G.ID,V.ID) AS ID, 
     C.TenderType AS TenderType1, 
     V.TenderType AS TenderType2, 
     G.TenderType AS TenderType3, 
     C.TenderAmount AS TenderAmount1, 
     V.TenderAmount AS TenderAmount2, 
     G.TenderAmount AS TenderAmount3 
FROM CashCTE C 
     FULL OUTER JOIN GiftCardCTE G 
      ON C.ID = G.ID 
     FULL OUTER JOIN CreditCardCTE V 
      ON C.ID = V.ID 

SQL Fiddle Demo