简体   繁体   中英

how to subtract to sum(produced from same table) in MYSQL?

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

query output:

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

how to do it in MYSQL?

You can simply:

SELECT (SELECT SUM(amount) FROM t WHERE `group` = 'a') -
       (SELECT SUM(amount) FROM t WHERE `group` = 'b') AS diff

Or:

SELECT SUM(CASE
           WHEN `group` = 'a' THEN  amount
           WHEN `group` = 'b' THEN -amount
       END) AS diff
FROM t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM