使用PIVOT滚动天数

时间:2013-01-03 14:05:02

标签: sql tsql sql-server-2008-r2 pivot

;WITH myRubbish AS
    (
    SELECT user, [20121231], [20130101], [20130102]
    FROM 
        ( 
        SELECT
            DateKey,
            user,
            revenue
        FROM    xxx.dbo.yyy
        WHERE DateKey > CONVERT(CHAR(8),GETDATE()-4,112)
        ) x
        PIVOT
        (
        SUM(revenue)
        FOR DateKey IN ([20121231], [20130101], [20130102]) 
        ) u
    )
SELECT * 
FROM myRubbish;

我如何调整它以便它可以每天运行并且列自动重新命名为过去3天?

1 个答案:

答案 0 :(得分:4)

您需要实现查询的动态SQL版本。与此类似:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(CHAR(8), DateKey, 112))
                    from xxx.dbo.yyy
                    WHERE DateKey > CONVERT(CHAR(8),GETDATE()-4,112)
                      -- and Datekey <= CONVERT(CHAR(8),GETDATE(),112) -- include this is you want to limit the records
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [user],' + @cols + ' from 
             (
                SELECT DateKey, [user], revenue
                FROM    xxx.dbo.yyy
                WHERE DateKey > CONVERT(CHAR(8),GETDATE()-4,112)
                  -- and Datekey <= CONVERT(CHAR(8),GETDATE(),112)  -- include this is you want to limit the records
            ) x
            pivot 
            (
                SUM(revenue)
                for DateKey in (' + @cols + ')
            ) p '

execute(@query)