简体   繁体   中英

How to sum rows and then subtract them grouped by?

CREATE TABLE test
    (`id` int, `type` int, `summ` int)
;

INSERT INTO test
    (`id`, `type`, `summ`)
VALUES
    (1, 1, 100),
    (2, 1, 200),
    (3, 2, 250),
    (4, 2, 20),
    (5, 3, 10)
;

sql:

SELECT
  type, SUM(summ) as total
FROM
  test
GROUP BY
  type

Result is 3 rows grouped by type and summed values of total : 1 - 300, 2 - 270, 3 - 10.

Q: How to subtract final total results from type 1 to all others ( 2 and 3 )? Result will be: 300 - 270 - 10 = 20. So, I need to get 20 as a result.

http://sqlfiddle.com/#!9/c4df28/1

You can use SUM and CASE :

SELECT SUM(CASE WHEN type = 1 THEN summ ELSE -summ END) as total
FROM test

SqlFiddleDemo

Records with type = 1 will be unchanged and rest will be negated.

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