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 に答える