Forum Discussion

EdSpa290's avatar
EdSpa290
Copper Contributor
Jun 19, 2025
Solved

Sql to calculate quarterly/annual aggregation aside of monthly numbers

Hi, I am struggling to calculate  amounts based on mtd amounts w/o using a cursor. Any idea?   create table #raw(quarter int, name varchar(10), year int, month int, amount decimal(19,2)) insert #...
  • EdSpa290's avatar
    Jun 19, 2025

    Actually, with temp tables:

     

    select mtd.quarter, mtd.name, mtd.year, mtd.month, mtd.amount, sum(ytd.amount) as ytd

    into #ytd

    from #raw mtd

    join #raw ytd on mtd.name = ytd.name and mtd.year = ytd.year and mtd.month >= ytd.month and mtd.quarter >= ytd.quarter

    group by mtd.quarter, mtd.name, mtd.year, mtd.month, mtd.amount

    order by 1,3,4,2

     

    select mtd.quarter, mtd.name, mtd.year, mtd.month, mtd.amount, sum(qtd.amount) as qtd

    into #qtd

    from #raw mtd

    join #raw qtd on mtd.name = qtd.name and mtd.year = qtd.year and mtd.month >= qtd.month and mtd.quarter = qtd.quarter

    group by mtd.quarter, mtd.name, mtd.year, mtd.month, mtd.amount

    order by 1,3,4,2

     

    select ytd.quarter, ytd.name, ytd.year, ytd.month, ytd.amount, qtd.qtd, ytd.ytd

    from #ytd ytd

    join #qtd qtd on qtd.name = ytd.name and qtd.year = ytd.year and qtd.month = ytd.month and qtd.quarter = ytd.quarter

    order by  1,3,4,2

Resources