MySQL在CASE语句中从SUM中减去

时间:2016-12-26 18:23:11

标签: mysql sql sum subtraction

我有一个SQL代码。

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

现在我需要从总和SUM中减去sales.amount,如果sales.type!= 51 AND sales.amount>我怎么能这样做?我想在ELSE声明之后我需要在第一个CASE声明中,但我不知道它是如何工作的。

例如,如果类型不是51并且sales.amount大于0,那么我应该从金额中减去它。

感谢。

1 个答案:

答案 0 :(得分:5)

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;