gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:49:27 24 4
gpt4 key购买 nike

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

结果为 3 行,按类型分组,总计的值分别为:1 - 300、2 - 270、3 - 10。

问:如何将最终total结果从类型1减去所有其他结果(2 >3)?结果将是:300 - 270 - 10 = 20。因此,我需要得到 20 结果。

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

最佳答案

您可以使用SUMCASE:

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

SqlFiddleDemo

type = 1 的记录将保持不变,其余记录将被否定。

关于php - 如何对行求和然后减去分组依据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com