2016-12-26 73 views
0

我有一個SQL代碼。MySQL在CASE語句中從SUM中減去

SELECT DISTINCT SQL_CALC_FOUND_ROWS 
       sales.code as code, 
       SUM(CASE WHEN sales.type = 51 THEN sales.amount ELSE 0 END) AS amount, 
       sales.type as type 
       FROM sales 

現在的事情是,我需要從總和減去sales.amount IF的sales.type!= 51和sales.amount> 0.我怎麼能做到這一點?我想我需要在ELSE語句之後的第一個CASE語句中,但我不知道這是如何工作的。

作爲例子,如果類型不是51並且它的sales.amount大於0,那麼我應該從數量中減去它。

謝謝。

回答

3

select distinct從哪裏來?使用GROUP BY

SELECT s.code as code, 
     SUM(CASE WHEN s.type = 51 THEN s.amount ELSE 0 END) AS amount 
FROM sales s 
GROUP BY s.code; 

然後回答你的問題是改變ELSE條款:

SELECT s.code as code, 
     SUM(CASE WHEN s.type = 51 THEN s.amount ELSE - s.amount 
      END) AS amount 
FROM sales s 
GROUP BY s.code;