sql >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo puedo contar los días de fin de semana de un rango de fechas?

Aquí está

DECLARE @STARTDATE DATE='01/JAN/2014'    
DECLARE @ENDDATE DATE='01/MAR/2014'

;WITH  CTE as
(
    SELECT  CAST(@STARTDATE AS DATE) as [DAYS] 
    UNION ALL
    SELECT DATEADD(DAY,1,[DAYS]) [DAYS]
    FROM    CTE
    WHERE   [DAYS] < CAST(@ENDDATE AS DATE)
)
SELECT DISTINCT COUNT([DAYS]) OVER(PARTITION BY DATENAME(WEEKDAY,[DAYS])) CNT,
DATENAME(WEEKDAY,[DAYS]) WD
FROM CTE 
WHERE DATENAME(WEEKDAY,[DAYS]) = 'SATURDAY' OR DATENAME(WEEKDAY,[DAYS]) = 'SUNDAY'
ORDER BY DATENAME(WEEKDAY,[DAYS]) 

Aquí está tu resultado