在SQL Server中查找上周的第一个日期

时间:2016-05-29 10:37:14

标签: sql sql-server sql-server-2012

我在SQL Server中有一些日期和周数,一周的第一天是5(星期五)。现在我想从下面的查询中计算上周和周开始日期。

scanf("%[^\n]s",string")

此查询的当前结果:

enter image description here

预期结果:

DECLARE @LocationID tinyint = 1,
     @FromDate date = '2016-05-20',
     @ToDate date = '2016-05-29';

--Step1: ==================================================================
--SET first day of the week of the year
DECLARE @CurrentDayOfWeek INT
SET DATEFIRST 1 -- normalize current dkoray of week to Monday
SET @CurrentDayOfWeek = DATEPART(DW, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0))
SET DATEFIRST @CurrentDayOfWeek -- first day of week is now 5 (Friday)

--SELECT @CurrentDayOfWeek

-----Get Weekend number--------------
DECLARE @WeekStart int, @WeekEnd int

SET @WeekStart=(SELECT { fn WEEK( @FromDate) })
SET @WeekEnd=(SELECT { fn WEEK( @ToDate) })

;WITH AllDate AS 
(
    SELECT @FromDate as TheDate
    UNION ALL
    SELECT DATEADD(DAY, 1, TheDate)
    FROM AllDate 
    WHERE DATEADD(DAY, 1, TheDate) <= @ToDate
),
AllDateDetail AS 
(
    SELECT TheDate, 
        DATEPART(WEEK, TheDate) AS WeekNumber,
        YEAR(TheDate) AS [Year], 
        UPPER(CONVERT(NVARCHAR(3),DATENAME(WEEKDAY, TheDate))) AS [DayName]        
    FROM AllDate
)
SELECT 
    *
    , CONVERT(DATE,DATEADD(WK, DATEDIFF(WK, 0, TheDate), 0)) AS LastWeekStart
    , { fn WEEK( CONVERT(DATE,DATEADD(WK, DATEDIFF(WK, 0, TheDate) - 1, 0))) } AS WeekNumber
FROM AllDateDetail


--Select dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) as LastWeekStart
--Select dateadd(wk, datediff(wk, 0, getdate()), 0) as ThisWeekStart
--Select dateadd(wk, datediff(wk, 0, getdate()) + 1, 0) as NextWeekStart
你能帮帮我吗?感谢

1 个答案:

答案 0 :(得分:6)

这是一些方便的方法来计算本周/上周的第一天/最后一天尊重我几周前写的DATEFIRST

SET DATEFIRST 5 --Friday
-- Start/End of Weeks respecting DATEFIRST
SELECT DATEADD(DAY,  1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) 'First Day of Current Week (DATEFIRST)';
SELECT DATEADD(DAY,  7-DATEPART(WEEKDAY, GETDATE()), GETDATE()) 'Last Day of Current Week (DATEFIRST)';
SELECT DATEADD(DAY, -6-DATEPART(WEEKDAY, GETDATE()), GETDATE()) 'First Day of Last Week (DATEFIRST)';
SELECT DATEADD(DAY,  0-DATEPART(WEEKDAY, GETDATE()), GETDATE()) 'Last Day of Last Week (DATEFIRST)';

(免费博客促销https://www.rednotebluenote.com/2016/04/first-day-of-the-week-and-datefirst/