使用datepart获取星期的开始日期

时间:2015-06-29 21:22:19

标签: sql

我有一个包含2列的表 - Date,ItemsSold。我有以下查询

Select datepart(week, [Date]) as WeekNo, SUM([ItemsSold]) as Total From [table] 
group by datepart(week, [Date])

这给出了以下输出

WeekNo   Total
3         20
4         30

我实际需要的是输出如下

WeekOf          Total
11 Jan 2015      20
18 Jan 2015      30

如何获取datepart返回的星期的开始日期?

1 个答案:

答案 0 :(得分:0)

对于SQL Server,如下所示:



declare @StartDate as datetime = '1/1/' + cast(datepart(year,getdate()) as char(4))
declare @StartofYear as datetime = dateadd(day,(datepart(dw,@startdate)*-1)+1,@StartDate)

Select datepart(week, [Date]) as WeekNo, SUM([ItemsSold]) as Total, dateadd(day,(@WeekNo-1)*7,@StartofYear) as WeekOf
From [table] 
group by datepart(week, [Date])