繁体   English   中英

计算两个总和

[英]Calculate sum of two sums

我有办法计算两个和的和吗? 接受以下查询(仅作为示例查询),如何获取combined_total的值? 当我运行查询时,它说total1是一个Unknown列。 有没有一种方法可以得到该值而不必将两个和相加而又求和? 这似乎是多余和混乱的。

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

暂无
暂无

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

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