2014-09-22 77 views
0

我試圖重新創建Tableau中的視圖作爲SQL中的視圖。它要求我旋轉基於一個月一個表,不僅總結了量,但我還需要通過保證金進行總結,並創建一個保證金%row.The所需的輸出是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

+0

我不明白保證金%。這是3個月的總和的百分比嗎?因此,1月將是(300/440)或68.1%2月將是18.18 3月13.63? – xQbert 2014-09-22 14:33:52

回答

0

不是最漂亮的SQL我已經做到了。但這似乎工作...

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

它的作用是建立在你已經通過產生一個邊界線並增加了總列 使用這條線,總那麼我們可以計算出%做了什麼的保證金。分組SETS允許我生成多行,小計和總計,因爲我知道生成的唯一附加行會有一個空類,所以我能夠在空類時將類的名稱設置爲邊界。

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'