TSQL Dynamic Pivot具有两个交替列

时间:2016-01-14 16:54:42

标签: sql sql-server tsql

我有一个表格,可以在多个日期向客户多次付款,如下所示:

Claimid  Payorder   Date Raised  Amount
79         1        05/12/2013   120000.00
79         2        19/10/2013   1138873.90
79         3        29/10/2013   150000.00
79         4        30/10/2013   11126.10
678        1        09/02/2006   467207.65

我需要转动数据,使它看起来像这样:

[Claimid]  [Date_Raised_1] [Payment_1]  [Date_Raised_2]  [Payment_2]
 79        05/12/2013        120000      19/10/2013       1138873.9

任何人都可以帮我吗? - 它也需要是动态的,因为任何索赔都可能有很多付款。

1 个答案:

答案 0 :(得分:0)

所以这就是我想出来的:

CREATE TABLE #Sample
(
    ClaimId INT
    , PayOrder INT
    , DateRaised DATE
    , Amount FLOAT
);

DECLARE @SQL VARCHAR(MAX) = 'SELECT ClaimId';

INSERT INTO #Sample (ClaimId, PayOrder, DateRaised, Amount)
VALUES (79, 1, CONVERT(DATE, '05/12/2013', 103), 120000.00)
    , (79, 2, CONVERT(DATE, '19/10/2013', 103), 1138873.90)
    , (79, 3, CONVERT(DATE, '29/10/2013', 103), 150000.00)
    , (79, 4, CONVERT(DATE, '30/10/2013', 103), 11126.10)
    , (678, 1, CONVERT(DATE, '09/02/2006', 103), 467207.65);

SELECT @SQL += '
    , MAX(CASE WHEN PayOrder = ' + PayOrder + ' THEN DateRaised END) AS [DateRaised_' + PayOrder + ']
    , MAX(CASE WHEN PayOrder = ' + PayOrder + ' THEN Amount END) AS [Payment_' + PayOrder + ']'
FROM (SELECT DISTINCT CONVERT(VARCHAR, PayOrder) AS PayOrder FROM #Sample) AS T
ORDER BY T.PayOrder;

SET @SQL += 'FROM #Sample GROUP BY ClaimId;';

EXECUTE (@SQL);

DROP TABLE #Sample;

此查询将为每个DISTINCT PayOrder生成列,并在您的测试用例中生成以下查询:

SELECT ClaimId
    , MAX(CASE WHEN PayOrder = 1 THEN DateRaised END) AS [DateRaised_1]
    , MAX(CASE WHEN PayOrder = 1 THEN Amount END) AS [Payment_1]
    , MAX(CASE WHEN PayOrder = 2 THEN DateRaised END) AS [DateRaised_2]
    , MAX(CASE WHEN PayOrder = 2 THEN Amount END) AS [Payment_2]
    , MAX(CASE WHEN PayOrder = 3 THEN DateRaised END) AS [DateRaised_3]
    , MAX(CASE WHEN PayOrder = 3 THEN Amount END) AS [Payment_3]
    , MAX(CASE WHEN PayOrder = 4 THEN DateRaised END) AS [DateRaised_4]
    , MAX(CASE WHEN PayOrder = 4 THEN Amount END) AS [Payment_4]
FROM #Sample
GROUP BY ClaimId;

输出结果:

╔═════════╦══════════════╦═══════════╦══════════════╦═══════════╦══════════════╦═══════════╦══════════════╦═══════════╗
║ ClaimId ║ DateRaised_1 ║ Payment_1 ║ DateRaised_2 ║ Payment_2 ║ DateRaised_3 ║ Payment_3 ║ DateRaised_4 ║ Payment_4 ║
╠═════════╬══════════════╬═══════════╬══════════════╬═══════════╬══════════════╬═══════════╬══════════════╬═══════════╣
║      79 ║ 2013-12-05   ║ 120000    ║ 2013-10-19   ║ 1138873.9 ║ 2013-10-29   ║ 150000    ║ 2013-10-30   ║ 11126.1   ║
║     678 ║ 2006-02-09   ║ 467207.65 ║ NULL         ║ NULL      ║ NULL         ║ NULL      ║ NULL         ║ NULL      ║
╚═════════╩══════════════╩═══════════╩══════════════╩═══════════╩══════════════╩═══════════╩══════════════╩═══════════╝

忽略日期格式,地雷设置为YYYY-MM-DD。它应该在您的计算机上显示为DD/MM/YYYY