amount group
--------------
100 'a'
40 'b'
30 'a'
50 'b'
查询输出:
diff(a-b)
---------
40
如何在MYSQL中做到这一点?
答案 0 :(得分:1)
您可以简单地:
SELECT (SELECT SUM(amount) FROM t WHERE `group` = 'a') -
(SELECT SUM(amount) FROM t WHERE `group` = 'b') AS diff
或者:
SELECT SUM(CASE
WHEN `group` = 'a' THEN amount
WHEN `group` = 'b' THEN -amount
END) AS diff
FROM t