3

OrderDate、TotalAmount のテーブルがあります。前月の合計金額を翌月に加算した月とその月のTotalAmountを表示したい。

例えば

OrderDate    TotalAmount  
----------   -----------  
13.01.1998---     10  
15.01.1998---     11  
01.02.1998---     12  
18.02.1998---     10  
12.03.1998---     09  

出力は

Month     TotalSum  
------    --------  
1---           21  
2---           43  
3---           52  
4

1 に答える 1

3

データが 1 暦年のみのものである場合は、次を使用できます。

with g as
( select month(orderdate) as ordermonth,
         sum( totalamount ) as sales
    from orders
    group by month(orderdate)
)
select m.ordermonth, sum(t.sales) as totalsales
  from g as m
  join g as t   on m.ordermonth >= t.ordermonth
  group by m.ordermonth
  order by m.ordermonth

ただし、データに 2 年が含まれる可能性がある場合は、そこにも年が必要になるため、年を含めるように月を構成します。

with g as
( select format(orderdate, 'yyyy-MM') as ordermonth,
         sum( totalamount ) as sales
    from orders
    group by format(orderdate, 'yyyy-MM')
)
select m.ordermonth, sum(t.sales) as totalsales
  from g as m
  join g as t   on m.ordermonth >= t.ordermonth
  group by m.ordermonth
  order by m.ordermonth
于 2013-09-08T07:00:30.157 に答える