2014-12-18 2 views
1

두 합계를 계산할 수있는 방법이 있습니까? 다음 쿼리 (예제 쿼리)를 가져와 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

당신은 별명'total1'와'total2'를 참조 할 수 있도록 하위 쿼리를 사용해야합니다. – Taryn

+0

나는 그걸로 돌아갈 수 있기를 바랐다 ... –

+0

코드를 반복하고 싶지 않으면 그 유일한 방법이다. – Taryn

답변

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

관련 문제