TSQL本周和下周的日期范围

时间:2015-03-18 19:45:52

标签: sql-server tsql stored-procedures sql-server-2012

我正在进行一项查询,我需要提供当前一周的日期范围内的会议总数以及下周范围内的数字。

我们的一周被视为周一至周日。在下面的代码中,我输出正确的日期,但我觉得有一个更清洁和有效的方法来实现这一目标。

任何人都可以对下面我的查询的替代方案有所了解,这将为我提供相同的结果吗?

DECLARE @TodayDayOfWeek INT
DECLARE @StartOfWeek DATETIME
DECLARE @EndOfWeek DATETIME
DECLARE @StartNextWeek DATETIME
DECLARE @EndNextWeek DATETIME
SET DATEFIRST 1; 


SET @TodayDayOfWeek = datepart(dw, GetDate())
SET @StartOfWeek = DATEADD(dd, -(@TodayDayOfWeek-1), GetDate())
SET @EndOfWeek = DATEADD(dd, -(@TodayDayOfWeek-7), GetDate())
SET @StartNextWeek = DATEADD(dd, -(@TodayDayOfWeek-8), GetDate())
SET @EndNextWeek = DATEADD(dd, -(@TodayDayOfWeek-14), GetDate())

SELECT @StartOfWeek
SELECT @EndOfWeek
SELECT @StartNextWeek
SELECT @EndNextWeek

1 个答案:

答案 0 :(得分:0)

SQL允许您使用DATEPART选择周数。他们对一周的定义从星期一开始,到星期日结束,所以和你的一样。您可以使用where子句来分类您想要的日期或按周分组,并计算每周的会议等...

    DECLARE @yourMeetings TABLE (MeetingDates DATE);

INSERT INTO @yourMeetings
VALUES  (GETDATE()),
        (DATEADD(DAY,1,GETDATE())),
        (DATEADD(DAY,2,GETDATE())),
        (DATEADD(DAY,3,GETDATE())),
        (DATEADD(DAY,4,GETDATE())),
        (DATEADD(DAY,5,GETDATE())),
        (DATEADD(DAY,6,GETDATE())),
        (DATEADD(DAY,7,GETDATE()));


SELECT *,
        DATEPART(wk,MeetingDates) AS Week_Num,
        DATENAME(WEEKDAY,MeetingDates) AS Day_Name
        /*COUNT(MeetingDates)*/
FROM @yourMeetings
--WHERE DATEPART(wk,MeetingDates) = 12;

/*GROUP BY DATEPART(wk,MeetingDates)*/

结果(今天是3月19日):

MeetingDates Week_Num    Day_Name
------------ ----------- ------------------------------
2015-03-19   12          Thursday
2015-03-20   12          Friday
2015-03-21   12          Saturday
2015-03-22   12          Sunday
2015-03-23   13          Monday
2015-03-24   13          Tuesday
2015-03-25   13          Wednesday
2015-03-26   13          Thursday