SQL query to compare product sales by month

后端 未结 6 1696
忘掉有多难
忘掉有多难 2021-02-10 07:45

I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:

Category | Revenue  |  Yearh  |  Month
B         


        
6条回答
  •  再見小時候
    2021-02-10 08:35

    Using pivot and Dynamic Sql we can achieve this result

    SET NOCOUNT ON
    IF OBJECT_ID('TEMPDB..#TEMP') IS NOT NULL
    DROP TABLE #TEMP
    
    ;With cte(Category , Revenue  ,  Yearh  ,  [Month])
    AS
    (
    SELECT 'Bikes', 10000, 2008,1 UNION ALL
    SELECT 'Bikes', 12000, 2008,2 UNION ALL
    SELECT 'Bikes', 12000, 2008,3 UNION ALL
    SELECT 'Bikes', 15000, 2008,1 UNION ALL
    SELECT 'Bikes', 11000, 2007,2 UNION ALL
    SELECT 'Bikes', 11500, 2007,3 UNION ALL
    SELECT 'Bikes', 15400, 2007,4
    )
    SELECT * INTO #Temp FROM cte
    
    Declare @Column nvarchar(max),
            @Column2 nvarchar(max),
            @Sql nvarchar(max)
    
    
    SELECT @Column=STUFF((SELECT DISTINCT ','+ 'ISNULL('+QUOTENAME(CAST(Yearh AS VArchar(10)))+','+'''0'''+')'+ 'AS '+ QUOTENAME(CAST(Yearh AS VArchar(10)))
    FROM #Temp order by 1 desc FOR XML PATH ('')),1,1,'')
    
    SELECT @Column2=STUFF((SELECT DISTINCT ','+ QUOTENAME(CAST(Yearh AS VArchar(10)))
    FROM #Temp FOR XML PATH ('')),1,1,'')
    
    SET @Sql= N'SELECT Category,[Month],'+ @Column +'FRom #Temp
                PIVOT
                (MIN(Revenue) FOR yearh IN ('+@Column2+')
                ) AS Pvt
    
                '
    EXEC(@Sql)
    Print @Sql
    

    Result

    Category    Month   2008    2007
    ----------------------------------
    Bikes       1       10000   0
    Bikes       2       12000   11000
    Bikes       3       12000   11500
    Bikes       4       0       15400
    

提交回复
热议问题