I need help figuring out how to compare the last run date to the current date and then calculate how many days between the two. I only need to compare the first row against the current date because I am sorting in descending order so that should be the last run date.
SELECT DISTINCT
cast(getdate() AS Date) AS Today, Run_Date, COUNT(Run_Date) AS Daily_Count,
Days_Since_Last_Run_Date =
CASE WHEN ROW_NUMBER() over (order by Run_Date) > 1 AND LAG(Run_Date,0) OVER (ORDER BY Run_Date) <> DATEADD(DAY,+1,Run_Date)
THEN + CAST((DATEDIFF(DAY,LAG(Run_Date,0) OVER (ORDER BY Run_Date),Run_Date)+1) AS NVARCHAR)
ELSE ''
END
FROM tblUnitsOfWork
WHERE Run_Date >= '2023-07-10'
GROUP BY Run_Date
ORDER BY Run_Date DESC;
1条答案
按热度按时间b1zrtrql1#
It is simpler to use a "nested" subquery (also called "derived table") to supply the row numbers, then in the outer query use a case expression. e.g:
fiddle
note: You do NOT need "select distinct" if you are using
GROUP BY
- grouping automatically includes making rows "distinct"To output empty strings in the different column convert that column to a string: