1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
DECLARE @DateFrom DATETIME = '2021-03-01 07:27:48.000';
DECLARE @DateTo DATETIME = '2021-03-04 12:12:58.000';
--Working time
DECLARE @WTFrom TIME = '07:00';
DECLARE @WTTo TIME = '15:00';
DECLARE @minCount BIGINT
-- Holidays
IF (OBJECT_ID(N'tempdb..#Holiday', N'U') IS NOT NULL)
DROP TABLE #Holiday;
CREATE TABLE #Holiday (holiday DATE)
INSERT INTO #Holiday VALUES ('20130101'), ('20130221');
--Date ranges
IF (DATEDIFF(HOUR, @DateFrom, @DateTo) > 12)
BEGIN
WITH CTE AS
(
SELECT @DateFrom AS DateVal
UNION ALL
SELECT DATEADD(HOUR, 1, DateVal)
FROM CTE
WHERE DateVal < DATEADD(HOUR, -1,@DateTo)
)
SELECT DATEDIFF(minute, MIN(CTE.DateVal), MAX(CTE.DateVal))
FROM CTE
WHERE (CAST(CTE.DateVal AS time) > @WTFrom AND CAST(CTE.DateVal AS time) < @WTTo) AND DATEPART(dw, CTE.DateVal) NOT IN (1, 7) AND NOT EXISTS (SELECT * FROM #Holiday AS H WHERE H.holiday = CTE.DateVal)
OPTION (MAXRECURSION 0);
END;
ELSE
BEGIN
WITH CTE AS
(
SELECT @DateFrom AS DateVal
UNION ALL
SELECT DATEADD(MINUTE, 1, DateVal)
FROM CTE
WHERE DateVal < DATEADD(MINUTE, -1,@DateTo)
)
SELECT DATEDIFF(minute, MIN(CTE.DateVal), MAX(CTE.DateVal))
FROM CTE
WHERE (CAST(CTE.DateVal AS time) > @WTFrom AND CAST(CTE.DateVal AS time) < @WTTo) AND DATEPART(dw, CTE.DateVal) NOT IN (1, 7) AND NOT EXISTS (SELECT * FROM #Holiday AS H WHERE H.holiday = CTE.DateVal)
OPTION (MAXRECURSION 0);
END; |
Partager