我有一个包含OrderDate,TotalAmount的表。我希望显示月份和月份的总量,以及下月的总量。
e.g。
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
答案 0 :(得分:3)
如果您的数据仅来自一个日历年,则可以使用
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
但是,如果您的数据有可能有两年的时间,那么您也需要年份,所以建立您的月份以包括年份。
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