T-SQL Datediff 함수의 주중 시작을 설정할 수 있습니까?
문제
나는 사용한다 데이트 디프 이번 주에만 추가 된 필터 레코드 기능 기능 :
DATEDIFF(week, DateCreated, GETDATE()) = 0
그리고 나는 일요일에 시작하는 것이 무엇인지 알았습니다. 그러나 제 경우에는 월요일에 일주일의 시작을 선호합니다. 어떻게 든 t-sql에서 가능합니까?
감사!
업데이트:
아래는 Datediff가 확인하지 않는 것을 보여주는 예입니다 @@ datefirst 변수 따라서 다른 솔루션이 필요합니다.
SET DATEFIRST 1;
SELECT
DateCreated,
DATEDIFF(week, DateCreated, CAST('20090725' AS DATETIME)) AS D25,
DATEDIFF(week, DateCreated, CAST('20090726' AS DATETIME)) AS D26
FROM
(
SELECT CAST('20090724' AS DATETIME) AS DateCreated
UNION
SELECT CAST('20090725' AS DATETIME) AS DateCreated
) AS T
산출:
DateCreated D25 D26
----------------------- ----------- -----------
2009-07-24 00:00:00.000 0 1
2009-07-25 00:00:00.000 0 1
(2 row(s) affected)
2009 년 7 월 26 일은 일요일이며, Datediff가 세 번째 열에서 0을 반환하고 싶습니다.
해결책
예 가능합니다
SET DATEFIRST 1; -- Monday
~에서 http://msdn.microsoft.com/en-us/library/ms181598.aspx
Datediff가 날짜를 존중하지 않는 것 같습니다.
create table #testDates (id int identity(1,1), dateAdded datetime)
insert into #testDates values ('2009-07-09 15:41:39.510') -- thu
insert into #testDates values ('2009-07-06 15:41:39.510') -- mon
insert into #testDates values ('2009-07-05 15:41:39.510') -- sun
insert into #testDates values ('2009-07-04 15:41:39.510') -- sat
SET DATEFIRST 7 -- Sunday (Default
select * from #testdates where datediff(ww, DATEADD(dd,-@@datefirst,dateadded), DATEADD(dd,-@@datefirst,getdate())) = 0
SET DATEFIRST 1 -- Monday
select * from #testdates where datediff(ww, DATEADD(dd,-@@datefirst,dateadded), DATEADD(dd,-@@datefirst,getdate())) = 0
도난당했습니다
다른 팁
다른 해결책이 있습니다. 이해하기가 더 쉬울 것입니다. 내가 틀렸다면 나를 수정합니다.
SET DATEFIRST 1
select DATEDIFF(week, 0, DATEADD(day, -@@DATEFIRST, '2018-04-15 00:00:00.000'))
우리는 날짜와 일요일부터 '-1'을 빼고 토요일이 될 것입니다 (7 일째 요일).
제휴하지 않습니다 StackOverflow