gpt4 book ai didi

mysql - 计算两个总和的总和

转载 作者:行者123 更新时间:2023-11-29 00:05:43 25 4
gpt4 key购买 nike

有没有办法计算两个和的总和?采用以下查询(只是一个示例查询)如何获取 combined_total 的值?当我运行查询时,它说 total1 是一个未知列。有没有办法获得该值而不必运行另一个结合两个总和的总和?这似乎是多余和困惑的。

select sum(
case when
the_date = date_sub(curdate(), interval 1 year)
then amount else 0 end
) as total1,
sum(
case when
the_date between date_sub(curdate(), interval 1 year)
and date_add(date_sub(curdate(), interval 1 year), interval 1 day)
then amount else 0 end
) as total2,
(total1 + total2) as combined_total

最佳答案

就像@bluefeet 提到的,子查询它,不要害怕。

CREATE TABLE tbl
(`type` varchar(1), `value` int, `active` int)
;

INSERT INTO tbl
(`type`, `value`, `active`)
VALUES
('a', 1, 1),
('a', 1, 1),
('b', 1, 0),
('b', 1, 1),
('b', 1, 1),
('c', 2, 1),
('c', 2, 0)
;

select
type,
sum_active,
sum_inactive,
sum_active+sum_inactive as total
from (
select
type,
sum(if(active=1,value,0)) as sum_active,
sum(if(active=0,value,0)) as sum_inactive
from tbl
group by type
) sums;

sqlfiddle:http://sqlfiddle.com/#!2/9699da/15/0

关于mysql - 计算两个总和的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27555671/

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