获取从星期一到星期日的当前工作日

时间:2013-10-08 07:09:48

标签: sql-server sql-server-2008

我试过解决方案就像这样。

select dateadd(wk, datediff(wk, 0, getdate()), 0)as StartDate ,
   (select dateadd(wk, datediff(wk, 0, getdate()), 0) + 5) as EndDate

它给出了星期一 - 星期六的结果,但在星期天它给了我下周的日子

我希望周日作为周的最后一天,周一作为周的第一天......

请帮助......

5 个答案:

答案 0 :(得分:10)

通常,使用SET DATEFIRST 1指定星期一是一周的第一天。但是,这并没有解决这个问题。请改用此语法:

SELECT DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0) AS StartWeek,
       DATEADD(week, DATEDIFF(day, 0, getdate())/7, 5) AS EndWeek

Demo

SET DATEFIRST (Transact-SQL)

1    Monday
2    Tuesday
3    Wednesday
4    Thursday
5    Friday
6    Saturday
7    (default, U.S. English) Sunday

答案 1 :(得分:1)

您只需添加6天而不是5天。

select dateadd(wk, datediff(wk, 0, getdate()), 0) as StartDate 
select dateadd(wk, datediff(wk, 0, getdate()), 0) + 6) as EndDate

答案 2 :(得分:0)

DECLARE
    @d datetime,
    @f datetime;

SET @d = dateadd(week,datediff(week,0,getdate())-48,0) --start of week from a year ago
SET @f = dateadd(week,datediff(week,0,getdate()),0) --start of current partial week;

create table #weeks (
    week_starting datetime primary key
)

while @d < @f
begin
    insert into #weeks (week_starting) values (@d)
    set @d = dateadd(week,1,@d)
end
select * from #weeks

drop table #weeks

答案 3 :(得分:0)

这可能过于复杂,但它很有趣。

- 第一部分是为了获得最近发生的星期一。

- 首先创建一个表,将所有日期保存到最近的星期一,然后将该表的min设置为@mondaythisweek变量。

declare @dateholder table (
    thedate date,
    theday varchar(10)
    )

declare @now datetime
set @now = GETDATE()

;with mycte as (
    select
        cast(@now as date) as "thedate",
        DATENAME(dw,@now) as "theday"
    union all
    select 
        cast(DATEADD(d,-1,"thedate") as date) as "thedate",
        DATENAME(DW,DATEADD(d,-1,"thedate")) as "theday"
    from
        mycte
    where
        "theday" <> 'Monday'
    )
insert into @dateholder
select * from mycte 
option (maxrecursion 10)

declare @mondaythisweek date
set @mondaythisweek  = (
select min(thedate)
from @dateholder
)

- 这部分创建了一个从@mondaythisweek到下一个星期日

的表格
;with mon_to_sun as (
    select
        @mondaythisweek as "dates",
        DATENAME(dw,@mondaythisweek) as "theday"
    union all 
    select
        cast(DATEADD(d,1,"dates") as date) as "dates",
        DATENAME(dw,cast(DATEADD(d,1,"dates") as date)) as "theday"
    from mon_to_sun
    where "theday" <> 'Sunday'
)
select * 
from mon_to_sun 
option(maxrecursion 10)

答案 4 :(得分:0)

SELECT DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 0) AS 'StartWeek(Monday)',
       DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 6) AS 'EndWeek(Sunday)'
  

随着时间

SELECT DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 0) AS 'StartWeek(Monday)',
       DATEADD(DAY,DATEDIFF(day, 0, DATEADD(week, DATEDIFF(day, 0, GETDATE())/7, 6)), '23:59:59') AS 'EndWeek(Sunday)'