需要有关多个支点的帮助

时间:2017-11-27 02:49:00

标签: sql-server pivot

我需要从以下数据中获取pivot数据:

AssetNo  EffectiveDate     Schedule         Interval
AIRT01      2017-11-23      2017-11-23  
AIRT01      2017-11-23      2017-12-23  
AIRT01      2017-11-23      2018-01-23  
AIRT01      2017-11-23      2018-02-23          3M
AIRT01      2017-11-23      2018-03-23  
AIRT01      2017-11-23      2018-04-23  
AIRT01      2017-11-23      2018-05-23          3M, 6M
AIRT01      2017-11-23      2018-06-23  
AIRT01      2017-11-23      2018-07-23  
AIRT01      2017-11-23      2018-08-23          3M
AIRT01      2017-11-23      2018-09-23  
AIRT01      2017-11-23      2018-10-23  
AIRT01      2017-11-23      2018-11-23          3M, 6M, 1Y

需要这样的输出:

    AssetNo EffectiveDate Nov-2017 Dec-2017 Jan-2018 Feb-2018 ... May-2018 ... Nov-2018
    AIRT01    2017-11-23                                3M         3M, 6M     3M, 6M, 1Y

是否可以获得多个pivot(对于时间表和间隔)?

1 个答案:

答案 0 :(得分:0)

试试这个答案:

DECLARE @cols NVARCHAR(MAX), @query NVARCHAR(MAX);
SET @cols = STUFF(
                 (
                     SELECT DISTINCT 
                            ','+QUOTENAME(RIGHT(CONVERT(VARCHAR, c.Schedule,113),8))
                            --','+QUOTENAME(c.Schedule)
                     FROM MyTab c FOR XML PATH(''), TYPE
                 ).value('.', 'nvarchar(max)'), 1, 1, '');
SET @query = 'SELECT [AssetNo],EffectiveDate, '+@cols+'from (SELECT 
           [AssetNo],
           EffectiveDate,
           [Interval] AS [amount],
           RIGHT(CONVERT(VARCHAR, Schedule,113),8) AS [category]
    FROM MyTab
    )x pivot (max(amount) for category in ('+@cols+')) p';
EXECUTE (@query);

希望这会对你有所帮助。

<强>输出

AssetNo EffectiveDate Nov 2017 Dec 2017 Jan 2018 Feb 2018 ... May 2018 ... Nov 2018
AIRT01    2017-11-23                                3M         3M, 6M     3M, 6M, 1Y