简体   繁体   中英

sql sum by month and year

在此处输入图片说明

I have tried by writing a correlated query but fails to result in output....I am trying using only joins now

SELECT sum(t1.acc)
    ,t1.mon
    ,t1.yr
FROM gl t1
WHERE mon IN (
        SELECT mon
        FROM gl t2
        WHERE t2.mon <= t1.mon
            AND t2.yr = t1.yr
        )
GROUP BY t1.mon
    ,t1.yr

You should join your data with itself and apply the sum condition.

drop table if exists #input_data

select * into #input_data
from
(
    select 1 as acc, 5  as mon, 2020 as yr union all
    select 2 as acc, 6  as mon, 2020 as yr union all
    select 3 as acc, 4  as mon, 2021 as yr union all
    select 4 as acc, 3  as mon, 2021 as yr
) d

select
    sum(e0.acc) as acc_sum,
    d.mon,
    d.yr
from 
    #input_data d
    join #input_data e0 
        on e0.yr = d.yr and e0.mon <= d.mon
group by
    d.yr, d.mon
order by
    d.yr, d.mon

If you have multiple records for same mon/yr then you have to add additional grouping.

drop table if exists #input_data

select * into #input_data
from
(
    select 1 as acc, 5  as mon, 2020 as yr union all
    select 2 as acc, 6  as mon, 2020 as yr union all
    select 3 as acc, 4  as mon, 2021 as yr union all
    select 4 as acc, 3  as mon, 2021 as yr union all
    select 0 as acc, 5  as mon, 2020 as yr 
) d

;with cte_source as 
(
    select
        sum(acc) as acc,
        mon,
        yr
    from #input_data d
    group by d.yr, d.mon
)
select
    sum(e0.acc) as acc_sum,
    d.mon,
    d.yr
from 
    cte_source d
    join cte_source e0 
        on e0.yr = d.yr and e0.mon <= d.mon
group by
    d.yr, d.mon
order by
    d.yr, d.mon

You seem to want a cumulative sum within a year:

select year, mon, sum(acc) over (partition by year order by mon)
from t
order by year, acc;

Getting the data back in the original order is a bit tricky but just requires an explicit order by .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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