DATEDIFF
conta transizioni , non punti (ad es. guarda DATEDIFF(year,'20161231','20170101')
). Considera anche la domenica come il primo giorno della settimana. Quindi, come compensiamo queste caratteristiche? Innanzitutto, spostiamo le nostre date in modo che i lunedì siano le nuove domeniche, e in secondo luogo aggiungiamo 1 per compensare l'errore del recinto:
declare @Samples table (
StartAt date not null,
EndAt date not null,
SampleName varchar(93) not null
)
insert into @Samples (StartAt,EndAt,SampleName) values
('20170101','20170131','Question - 6'),
('20170102','20170129','Exactly 4'),
('20170102','20170125','3 and a bit, round to 4'),
('20170101','20170129','4 and 1 day, round to 5')
--DATEDIFF counts *transitions*, and always considers Sunday the first day of the week
--We subtract a day from each date so that we're effectively treating Monday as the first day of the week
--We also add one because DATEDIFF counts transitions but we want periods (FencePost/FencePanel)
select *,
DATEDIFF(WEEK, DATEADD(day,-1,StartAt), DATEADD(day,-1,EndAt)) +1
as NumWeeks
from @Samples
Risultati:
StartAt EndAt SampleName NumWeeks
---------- ---------- -------------------------- -----------
2017-01-01 2017-01-31 Question - 6 6
2017-01-02 2017-01-29 Exactly 4 4
2017-01-02 2017-01-25 3 and a bit, round to 4 4
2017-01-01 2017-01-29 4 and 1 day, round to 5 5
Se questo non corrisponde a ciò che desideri, forse puoi adottare e adattare il mio @Samples
tabella per mostrare i risultati che ti aspetti.