SQL:包含总和和百分比的数据透视表

时间:2014-09-22 13:41:45

标签: sql pivot

我尝试在Tableau中重新创建一个视图作为SQL中的视图。它需要我基于月份来旋转表格,不仅要求总和金额,还需要按保证金加总,还要创建保证金%行。所需的输出是

BUSINESS_UNIT   CLASS          JANUARY  FEBRUARY    MARCH
202            Cost of Sales    100    (null)       60
202            Revenue          200    80           (null)
202            Margin           x      xx           xxx
202            Margin %         x%     xx%          xxx%

我可以根据月份进行调整,但是如何在一个数据透视表中执行两次总结以及如何包含一个percenatge行呢?

到目前为止

代码

SELECT 
    *
FROM
    (SELECT
            [Business_Unit]
            ,[Class]
            ,Month as Period
            ,[Amount]
            --,Margin                               
      FROM [sample_table]
      where [Class] in ('Revenue','Cost of Sales') )AS T
    PIVOT(SUM(Amount)
            FOR Period IN ([January],[February],[March])) as Pvt

到目前为止我已经包含了我的代码http://www.sqlfiddle.com/#!3/06bafc/6

1 个答案:

答案 0 :(得分:0)

不是我做过的最漂亮的SQL。但这似乎有用......

http://www.sqlfiddle.com/#!3/06bafc/60/0

它的作用是通过生成边距线并添加总列来建立您已完成的工作 使用此行和总计,我们可以计算保证金的百分比。分组SETS允许我生成多行,小计和总计,因为我知道生成的唯一额外行将具有空类,所以我能够在null时将类的名称设置为margin。

WITH CTE AS (
    SELECT 
      Business_Unit
      ,case when class is NULL then 'Margin' else class end as Class
      ,Sum(January) as January
      ,Sum(February) as February 
      ,Sum(March) as march
      ,Sum(coalesce(January,0)+coalesce(February,0)+coalesce(March,0)) as Total
    FROM (
      SELECT 
        *
      FROM
        (SELECT
                [Business_Unit]
                ,[Class]
                ,Month as Period
                ,[Amount]
                --,Margin                               
          FROM [sample_table]
          where [Class] in ('Revenue','Cost of Sales') )AS T
        PIVOT(SUM(Amount)
                FOR Period IN ([January],[February],[March])) as Pvt
      ) as Base
    GROUP BY Grouping sets 
    ((Business_Unit,Class,January,February,March,
      coalesce(January,0)+coalesce(February,0)+coalesce(March,0))
     ,(Business_Unit)
     ))
    SELECT * 
    FROM  CTE UNION
    SELECT Business_Unit
      ,'Margin %'
      ,January*100.00/Total
      ,February*100.00/Total
      ,March*100.00/Total
      ,Total*100.00/Total
    FROM CTE
    WHERE CLASS='Margin'