截止日期结束日期

时间:2015-03-09 22:35:30

标签: sql sql-server tsql views

我有一个视图,我需要显示每行的周末日期。我使用了以下查询:

SELECT     TOP (100) PERCENT [Delivery Date], [Delivery Method], [Order Total], YEAR([Delivery Date]) AS Year, DATEADD(d, 7 - DATEPART(dw, [Delivery Date]), [Delivery Date]) 
                      AS WeekEnd
FROM         dbo.salesdata
ORDER BY [Delivery Date] DESC

运作良好,但周末日期是基于星期日是一周的第一天而不是星期一,这是新西兰的标准。

我环顾四周,看起来唯一可行的选项是设置DATEFIRST,但是你不能在视图中使用它。

请帮忙!

1 个答案:

答案 0 :(得分:1)

请尝试以下操作,以便在某一天前进但不会在一周开始时跳闸。这里的关键是模数'%',它将调整的天数回滚到开头。如果您的星期在星期三开始,您只需将“+ 1”替换为“+ 3”,一切都会有效。

DATEADD(d, (7 - DATEPART(dw, [Delivery Date]) + 1) % 7, [Delivery Date]) AS WeekEnd

SELECT TOP (100) PERCENT
    [Delivery Date],
    [Delivery Method],
    [Order Total],
    YEAR([Delivery Date]) AS Year,
    DATEADD(d, (7 - DATEPART(dw, [Delivery Date]) + 1) % 7, [Delivery Date]) AS WeekEnd
FROM dbo.salesdata
ORDER BY [Delivery Date] DESC