Pergunta

Eu uso DATEDIFF função para filtrar registros adicionados esta semana apenas:

DATEDIFF(week, DateCreated, GETDATE()) = 0

e notei que é assumido o que semana começa no domingo. Mas no meu caso eu preferiria set início da semana na segunda-feira. É possível de alguma forma em T-SQL?

Obrigado!


Update:

Abaixo está um exemplo mostrando o que DATEDIFF não verifica @@ DATEFIRST variável então eu preciso de uma outra solução.

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

Output:

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)

26 de julho de 2009 é domingo, e eu quero DATEDIFF retorna 0 na terceira coluna também.

Foi útil?

Solução

Sim possível

SET DATEFIRST 1; -- Monday

http://msdn.microsoft.com/en-us/library /ms181598.aspx

Parece datediff não respeita a DATEFIRST, assim torná-lo fazê-lo executá-lo como este

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

Stolen from

http: // social.msdn.microsoft.com/Forums/en-US/transactsql/thread/8cc3493a-7ae5-4759-ab2a-e7683165320b

Outras dicas

Eu tenho uma outra solução. Este deve ser mais fácil de entender, me corrija se eu estiver errado

SET DATEFIRST 1
select DATEDIFF(week, 0, DATEADD(day, -@@DATEFIRST, '2018-04-15 00:00:00.000'))

Nós subtrair '-1' a partir da data e domingo se tornará sábado (que é dia 7nth de semana) e Mond?y (2) irá primeiro dia da semana

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top