2017-08-02 58 views
0

這裏做一個子查詢內的聚合函數的輸入表:帳戶需要通過轉換行到列

accountnumber year quarter catgeory owedamt payedamt writeoffamt 
101   2001  1  Tax   130.0  0.0   30.0 
101   2001  1  Interest 130.0  30.0  30.0 
101   2001  2  Interest 120.0  20.0  20.0 
102   2002  1  Interest 120.0  100.0  20.0 
102   2002  2  Tax   110.0  100.0  10.0 

輸出

accountnumber year quarter Tax (outstanding)  Interest (outstanding) 
101   2001  1   100.0      70.0 
101   2001  2   0.0      80.0 
102   2002  2   10.0      0.0 

這裏的「優秀」是caluclated總和的基礎上(OWED_AMT - (PAID_AMT + WRITEOFF_AMT))作爲未知數

注意:我們需要將列作爲稅和利息,但這些列中的金額應該是未完成的,這是在t他是以上公式的基礎。

注2:用於accountntumber:102,興趣(優秀)被計算
總和(OWED_AMT - (PAID_AMT + WRITEOFF_AMT)),其是(120-(100 + 20))= 0.0

但是,我們不要在該年度的任何稅種和四分之一所以輸出結果0.0

如果我們在同一年同一季度有兩種稅(優秀)和利息(優秀)爲零,我們可以跳過該行

我正在使用的查詢是:

with summaryData (accountnumber , 
      year , 
      quarter, tax, interest) as 
(
    SELECT accountnumber , 
      year , 
      quarter , 
      SUM(CASE WHEN catgeory = 'Tax' THEN sum(OWED_AMT - (PAID_AMT + WRITEOFF_AMT)) 
        ELSE 0 
       END), 
      SUM(CASE WHEN catgeory = 'Interest' THEN sum(OWED_AMT - (PAID_AMT + WRITEOFF_AMT)) 
        ELSE 0 
       END) 
    FROM acccount 
    GROUP BY accountnumber , 
      year , 
      quarter 
) 
select * from summaryData 
where tax > 0 or interest > 0; 

我在這裏得到的錯誤是:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery. 

回答

2

你並不需要在CTE的嵌套聚合。所以:

with summaryData (accountnumber, year, quarter, tax, interest) as (
     SELECT accountnumber, year, quarter, 
      SUM(CASE WHEN catgeory = 'Tax' THEN OWED_AMT - (PAID_AMT + WRITEOFF_AMT) 
         ELSE 0 
       END), 
      SUM(CASE WHEN catgeory = 'Interest' THEN OWED_AMT - (PAID_AMT + WRITEOFF_AMT) 
         ELSE 0 
       END) 
     FROM acccount 
     GROUP BY accountnumber, year, quarter 
    )