简体   繁体   English

如何对行求和,然后减去分组依据?

[英]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: 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. 结果是3行,按type和总计值的total分组:1-300、2-270、3-10。

Q: How to subtract final total results from type 1 to all others ( 2 and 3 )? 问:如何将类型1最终total结果减去所有其他结果( 23 )? Result will be: 300 - 270 - 10 = 20. So, I need to get 20 as a result. 结果将是:300-270-10 =20。因此,我需要得到20

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

You can use SUM and CASE : 您可以使用SUMCASE

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. type = 1记录将保持不变,其余的将被否定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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