如何在MYSQL中减去(从同一表产生)总和?

时间:2019-01-28 14:12:14

标签: mysql sql group-by

amount  group
--------------
 100     'a'
  40     'b'
  30     'a'
  50     'b'

查询输出:

diff(a-b)
---------
  40

如何在MYSQL中做到这一点?

1 个答案:

答案 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