DECLARE @StartDate DATE = :dd
DECLARE @endDate DATE = :dd1
DECLARE @StartTime1 TIME = '06:15:00';
DECLARE @EndTime1 TIME = '14:46:00';
DECLARE @StartTime2 TIME = '14:45:00';
DECLARE @EndTime2 TIME = '23:16:00';
DECLARE @StartTime3 TIME = '23:15:00';
DECLARE @EndTime3 TIME = '06:16:00';
WITH DateSequence AS (
SELECT @StartDate AS CurrentDate
UNION ALL
SELECT DATEADD(DAY, 1, CurrentDate)
FROM DateSequence
WHERE DATEADD(DAY, 1, CurrentDate) <= @endDate
)
SELECT
ds.CurrentDate,
COALESCE(MAX(CONVERT(FLOAT, KWH)) - MIN(CONVERT(FLOAT, KWH)), 0) AS Diff
FROM DateSequence ds
LEFT JOIN Main m ON ds.CurrentDate = CAST(m.Date AS DATE)
WHERE BG = :bg
AND Plant = :pl
AND Line = :ll
AND Machine = :ma
AND
(
(
m.Date >= CAST(ds.CurrentDate AS DATETIME) + CAST(@StartTime3 AS DATETIME) AND m.Date <= CAST(ds.CurrentDate AS DATETIME) + CAST('23:59:59' AS DATETIME)
)
OR
(
m.Date >= CAST(DATEADD(DAY, 1, ds.CurrentDate) AS DATETIME) AND m.Date <= CAST(DATEADD(DAY, 1, ds.CurrentDate) AS DATETIME) + CAST(@EndTime3 AS DATETIME)
)
)
GROUP BY ds.CurrentDate
ORDER BY ds.CurrentDate;
while fetching the data from main Table using above query the data is computing till start time 3 i.e., till 11:59:00pm of the current day...the data from 12:00:AM to 06:15 AM end time 3 data is not fetching correctly and it got missed in the calculation what modification we need to do in the where condition