我的SUM条件为负整数会导致计算错误。
如果CN(贷方)为true,则必须将该行的总计设置为负,然后将总计加在一起。
+----+-------+------------+-------+
| id | CN | date | total |
+----+-------+------------+-------+
| 1 | false | 2019-01-01 | 30 |
+----+-------+------------+-------+
| 2 | true | 2019-01-01 | 15 |
+----+-------+------------+-------+
SELECT
MONTH(invoices.date) as month,
IF(invoices.CN = true,
CAST(SUM(DISTINCT COALESCE(invoices.total * -1, 0)) AS SIGNED),
CAST(SUM(DISTINCT COALESCE(invoices.total, 0)) AS SIGNED)) AS total,
from invoices
GROUP BY month
结果
+-------+------+
| month | total|
+-------+------+
| 1 | -30 |
+-------+------+
我期望:30 +(-15)= 15
+-------+------+
| month | total|
+-------+------+
| 1 | 15 |
+-------+------+
答案 0 :(得分:4)
这符合您的想法:
SELECT
MONTH(date) AS month,
SUM(CASE WHEN CN = 'true' THEN -1.0 * total ELSE total END) AS total
FROM invoices
GROUP BY
MONTH(date);
我说这很接近,因为目前尚不清楚CN
如何或为什么最终出现在汇总结果中。对我来说,只报告月份和总数是很有意义的。
答案 1 :(得分:4)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (cn TINYINT, total INT);
INSERT INTO my_table VALUES (false,30),(true,15);
SELECT SUM((0.5-cn)*2*total)x FROM my_table;
+------+
| x |
+------+
| 15.0 |
+------+
1 row in set (0.00 sec)