Sto cercando di capire come calcolare il numero di “martedì” tra due date in TSQL?
“Martedì” potrebbe essere qualsiasi valore.
Grazie t-clausen.dk, mi ha salvato pochi giorni. Per non ottenere istanze di ogni giorno:
declare @from datetime= '3/1/2013' declare @to datetime = '3/31/2013' select datediff(day, -7, @to)/7-datediff(day, -6, @from)/7 AS MON, datediff(day, -6, @to)/7-datediff(day, -5, @from)/7 AS TUE, datediff(day, -5, @to)/7-datediff(day, -4, @from)/7 AS WED, datediff(day, -4, @to)/7-datediff(day, -3, @from)/7 AS THU, datediff(day, -3, @to)/7-datediff(day, -2, @from)/7 AS FRI, datediff(day, -2, @to)/7-datediff(day, -1, @from)/7 AS SAT, datediff(day, -1, @to)/7-datediff(day, 0, @from)/7 AS SUN
declare @from datetime= '9/20/2011' declare @to datetime = '9/28/2011' select datediff(day, -6, @to)/7-datediff(day, -5, @from)/7
@ t-clausen.dk e Andriy M come risposta alla risposta e ai commenti di t-clausen.dks
La query utilizza il fatto che il 1900-01-01 era un lunedì. E il 1900-01-01 è la data 0.
select dateadd(day,0,0)
Il secondo parametro nella funzione datediff
è la data di datediff
.
Quindi stai confrontando ‘1899-12-26’ con il tuo @ to-date e ‘1899-12-26’ è un martedì
select datename(dw,dateadd(day, 0, -6)), datename(dw, '1899-12-26')
Stessa cosa per il secondo appuntamento che usa lo stesso fatto.
In realtà è ansible confrontare con qualsiasi martedì conosciuto e mercoledì corrispondente (che non è nell’intervallo di date che si sta studiando).
declare @from datetime= '2011-09-19' declare @to datetime = '2011-10-15' select datediff(day, '2011-09-13', @to)/7-datediff(day, '2011-09-14', @from)/7 as [works] ,datediff(day, '2011-10-18', @to)/7-datediff(day, '2011-10-19', @from)/7 as [works too] ,datediff(day, '2011-09-27', @to)/7-datediff(day, '2011-09-28', @from)/7 as [dont work]
Fondamentalmente l’algoritmo è “Tutti i martedì meno tutti i mercoledì”.
Dai un’occhiata a questa domanda: conta i giorni lavorativi tra due date
Ci sono alcuni modi in cui puoi sfruttare la risposta a questa domanda anche per il tuo.