如何从WeekNumber和Year TSQL开始周开始日期(星期一)

时间:2016-04-22 08:15:26

标签: tsql

嗨我有一个要求,我已经给出了一周内一年的通话总数。

CREATE UNIQUE INDEX [IX_DI_VirtualItemCode] ON [dimensionitems] (    [vitemcode] ASC)​
CREATE UNIQUE INDEX [IX_DI_VirtualItemCode_dimvalue1_dimvalue2] ON [dimensionitems] (    [vitemcode] ASC,    [dimvalue1] ASC,    [dimvalue2] ASC)

我想在此数据中添加weekCommence Date和Month。任何人请告诉我如何/如果我可以用现有的数据实现这一目标?

1 个答案:

答案 0 :(得分:0)

要获得当前周的开始日期,您可以使用以下公式:

SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) MondayOfCurrentWeek

因此,如果您的表有一个CallDateTime字段,那么您的查询可能是:

select datepart(wk, CallDateTime) as Week, 
datepart(day, DATEADD(week, DATEDIFF(week, 0, CallDateTime), 0) ) WeekMonday,
datepart(day, DATEADD(week, DATEDIFF(week, 0, CallDateTime), 0) ) WeekMonth,
datepart(year, CallDateTime) as Year, 
count(*) as TotalCalls
from CallTable
group by datepart(wk, CallDateTime), 
datepart(day, DATEADD(week, DATEDIFF(week, 0, CallDateTime), 0) ),
datepart(day, DATEADD(week, DATEDIFF(week, 0, CallDateTime), 0) ),
datepart(year, CallDateTime)