简体   繁体   English

如何在 sql server 2008 中获取一周的第一天和一周的最后一天?

[英]How to get first day of the week and last day of the week in sql server 2008?

How to get the first day of the week and last day of the week when we input any one day of a week?当我们输入一周中的任何一天时,如何获得一周的第一天和一周的最后一天?

For example if we enter a date then the first(Monday) and last (Friday) day should be displayed.例如,如果我们输入一个日期,那么应该显示第一天(星期一)和最后一天(星期五)。 that is if we enter 24-jan-2014 then 20-jan-2014 and 24-jan-2014 should be displayed.也就是说,如果我们输入 24-jan-2014,那么应该显示 20-jan-2014 和 24-jan-2014。

Regards问候

Here's how you can do it:您可以这样做:

DECLARE @yourdate date = getdate()
Select dateadd(ww, datediff(ww, 0, @yourdate), 0)
Select dateadd(ww, datediff(ww, 0, @yourdate), 4)

You set @yourdate to the date you want.您将@yourdate设置为您想要的日期。 The first SELECT will give you the first day and the second SELECT will give you the last date第一个 SELECT 会给你第一天,第二个 SELECT 会给你最后一个日期

Try this尝试这个

SELECT DATEADD(wk, DATEDIFF(wk, 6, '5/13/2005'), 6)
SELECT DATEADD(wk, DATEDIFF(wk, 5, '5/13/2005'), 5)

(Or) (或者)

Declare @Date datetime
Det @Date = '2012-04-12'
Delect @Date - DATEPART(dw, @Date) + 1 FirstDateOfWeek,
       @Date + (7 - DATEPART(dw, @Date)) LastDateOfWeek

这解决了它,并在年末结束:

SELECT DATEADD(wk, DATEDIFF(d, 0, '01 January 2017') / 7, 0)

With a calendar date already loaded, group can be done like this for all the years existing in the table =)已加载日历日期后,可以对表中存在的所有年份进行分组 =)

select 
Y,
M,
(Select dateadd(ww, datediff(ww, 0, dt), 0) ) wk_str_dt ,
(Select dateadd(ww, datediff(ww, 0, dt), 4)  )wk_end_dt , 
dt recd_crt_dt
from [tcalendar]
where  isWeekday= 1 
AND DW = 2 -- only mondays
order by Y, W 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM