有一个需求:对每个月每周求销售总额。
我们知道SQL有函数datepart(week,Getdate())能返回当前年的第几周。(年周数)
select datepart(week,'2012-05-02') --Answer:18
不过,可以用当前天的年周数,减去月初那天的年周数,再加一,就可以得到月周数。
原始数据:
select * from ProductAndTime
之后算出当前月的第一天:
再将两个日期求年周数想减加一就得到了月周数。顺便,加一个月份,以备后面使用。
最后,对月和月周数汇总就能得到最终答案了。
全部代码:
with cte as
(
select SalesAmount
,YearMonth=CONVERT(varchar(7),FullDateAlternateKey,121)
,WeekOfMonth=datepart(week,FullDateAlternateKey)-datepart(week,CONVERT(varchar(8),FullDateAlternateKey,121)+'01')+1
from ProductAndTime
)
select SUM(SalesAmount) AS SumAmount
,YearMonth
,WeekOfMonth
from cte
group by YearMonth,WeekOfMonth
order by YearMonth,WeekOfMonth
That's all :P