SQL Server PIVOT Column Data

后端 未结 1 700
情歌与酒
情歌与酒 2020-12-06 22:51

I have a table with data as given below:

DATE            Price
----------      ------
31/12/2009  10
31/12/2009  11
31/12/2009  12
30/12/2009  20
30/12/2009          


        
相关标签:
1条回答
  • 2020-12-06 23:31

    OK, as I mentioned, your data does not make sense, but maybe this can help.

    The only way to create a dynamic pivot, is by creating dynamic sql.

    Also, PIVOT requires that you use an Aggregate function (SUM, AVG, COUNT).

    Ok, let see if this can help you.

    CREATE TABLE #TEMP  (EffectiveDate DATETIME,Price INT) 
    INSERT INTO #TEMP(EffectiveDate,Price) 
    SELECT GETDATE(),10 
    UNION ALL 
    SELECT GETDATE(),11 
    UNION ALL 
    SELECT GETDATE(),12 
    UNION ALL 
    SELECT GETDATE()-1,20 
    UNION ALL 
    SELECT GETDATE()-1,21 
    UNION ALL 
    SELECT GETDATE()-1,22 
    UNION ALL 
    SELECT GETDATE()-2,30 
    UNION ALL 
    SELECT GETDATE()-2,32 
    UNION ALL 
    SELECT GETDATE()-2,31 
    
    DECLARE @Cols VARCHAR(MAX)
    SELECT @cols = COALESCE(@cols + ',[' + colName + ']',
                             '[' + colName + ']')
    FROM    (
                SELECT DISTINCT 
                        CONVERT(VARCHAR,EffectiveDATE,103) colName
                FROM    #TEMP
            ) s
    ORDER BY colName DESC
    
    DECLARE @query VARCHAR(MAX)
    SET @query = N'SELECT *
    FROM
    (SELECT CONVERT(VARCHAR,EffectiveDATE,103) AS ''DATE'',Price
                FROM    #TEMP) p
    PIVOT
    (
    SUM(Price) FOR DATE IN
    ( '+
    @cols +' )
    ) AS pvt' 
    
    EXECUTE(@query)
    
    
    DROP TABLE #TEMP
    
    0 讨论(0)
提交回复
热议问题