I have to create a query to return results for a multi-axis chart. I need to count the number of Ids created for each date between 2 dates. I tried this:
DECLARE @StartDate datetime2(7) = '11/1/2020',
@EndDate datetime2(7) = '2/22/2021'
;WITH Date_Range_T(d_range) AS
(
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, @EndDate) - @StartDate, 0)
UNION ALL SELECT DATEADD(DAY, 1, d_range)
FROM Date_Range_T
WHERE DATEADD(DAY, 1, d_range) < @EndDate
)
SELECT d_range, COUNT(Id) as Total
FROM Date_Range_T
LEFT JOIN [tbl_Support_Requests] on ([tbl_Support_Requests].CreatedDate Between @StartDate AND @EndDate)
GROUP BY d_range ORDER BY d_range ASC
Of course, the problem is with the ;WITH
which returns the error
Operand type clash: datetime2 is incompatible with int.
The above works if I give it a specific number of days from the current date like:
;WITH Date_Range_T(d_range) AS
(
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 6, 0)
UNION ALL SELECT DATEADD(DAY, 1, d_range)
FROM Date_Range_T
WHERE DATEADD(DAY, 1, d_range) < GETDATE()
)
Which returns:
The problem is that I cannot figure out how to substitute the date range.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…