2017-08-24 57 views
-1

添加量的總和需要得到量的總和基於以下條件的表emp:需要從一個case語句

empid yearquarter  type status amount orderdate 
101  20151   1 A  3000  01-18-2015 
101  20152   3 A  4000  05-09-2015 
101  20152   4 A  5000  06-09-2015 
101  20152   4 P  5000  06-09-2015 
101  20152   1 A  7000  06-09-2015 
101  20153   6 A  9000  09-11-2015 
101  20153   7 A  10000 09-11-2015 
101  20154   3 A  2000  12-12-2015 

條件1:只需添加狀態=「A」和比(3,4)與各自的yearquarter其他類型

條件2:如果在某一去年同期只有類型(3,4)和狀態=「A」,我們可以將它們添加

FROM上述條件

在20151,我們只有1只記錄1型 就需要從3000

在20152,我們只有1個紀錄類型:1 就需要從7000(我們需要忽略不同類型的所有其他記錄)

在20153有類型的(6,7) 就需要從19000

IN 20154兩條記錄,只有TYPE:3記錄就需要從2000

so the total output needed is:31000 

31000應顯示

+1

你有什麼試過的?這不是一個代碼寫入服務。 – nicomp

+1

停止滾動回大喊 – Lamak

+0

我要爲兩種不同情況的案例陳述,但總結總計我不能 –

回答

0

試試這個應該足夠你的要求

select case when status ='A' AND type in (3,4) then SUM(amount) as amount 
      when status ='A' AND type not in (3,4) then yearquarter,amount end 
0

這是由條件的多層複雜。如果我理解正確:

select yearquarter, 
     (case when sum(case when type not in (3, 4) then 1 else 0 end) = 0 
      then sum(amount) 
      else sum(case when type not in (3, 4) then amount else 0 end) 
     end) 
from t 
where status = 'A' 
group by yearquarter; 
+0

我已經修改了這個問題......您共享的查詢正在挑選錯誤的值 –

+0

如何將年度總額添加到單個值中 –