我有一个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,那么我应该从金额中减去它。
感谢。
答案 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;