2013-10-08 178 views
8

我已經嘗試瞭解決此問題的方法。從星期一到星期日獲取當週工作日

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

它給出了結果週一至週六,但上週日它給了我下個星期天

我想週日的一週,週一爲一週的第一天的最後一天..

請幫助...

+0

你需要看看這個答案[獲取在SQL Server一週的第一天(HTTP:/ /stackoverflow.com/a/7169656/1297603) – Yaroslav

回答

9

通常,使用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 
+0

非常感謝,我從中得到了所需的解決方案。 – saylesh

+0

完美答案。謝謝 –

1

您只需加6天,而不是5

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

錯誤:錯誤的語法錯誤 –

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 
0

這可能過於複雜,但它很有趣。

- 第一部分是獲取最近發生的星期一。

- 它首先創建一個表,它將保存所有日期直到最近一個星期一,然後將該表的最小值設置爲@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) 
相關問題