1
;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 天?

4

1 回答 1

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)
于 2013-01-03T14:09:17.120 回答