我有办法计算两笔钱的总和吗?采取以下查询(只是一个示例查询)如何获取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
答案 0 :(得分:1)
就像@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