[英]Calculate sum of two sums
Is there a way for me to calculate the sum of two sums? 我有办法计算两个和的和吗? Take the following query (just an example query) how can I get a value for
combined_total
? 接受以下查询(仅作为示例查询),如何获取
combined_total
的值? when I run my query it says total1
is an Unknown column. 当我运行查询时,它说
total1
是一个Unknown列。 Is there a way to get that value without having to run another sum combining the two sums? 有没有一种方法可以得到该值而不必将两个和相加而又求和? That just seems redundant and messy.
这似乎是多余和混乱的。
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
Just like @bluefeet mentioned, subquery it, and fear not. 就像@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 sqlfiddle: http ://sqlfiddle.com/#!2/9699da/15/0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.