将多行组合成一行,使用单独的列

时间:2014-09-04 15:03:11

标签: sql sql-server sql-server-2005

我正在尝试编写一个查询,其中我加入的其中一个表可能包含每个唯一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.任何帮助都会很棒。

3 个答案:

答案 0 :(得分:0)

这是一个'枢轴'。您应该查看如何进行数据透视表。

答案 1 :(得分: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

答案 2 :(得分:0)

使用SQL Pivot完成此任务。此链接中的说明和示例:

http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx