SQL Server Compare run date to current date

dw1jzc5e  于 2023-08-02  发布在  其他
关注(0)|答案(1)|浏览(115)

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;

b1zrtrql

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:

SELECT
    *
    , case when rn = 1 then datediff(day,run_date,getdate()) end as days_diff
FROM (
    SELECT
          cast(getdate() AS DATE) AS Today
        , Run_Date
        , COUNT(Run_Date) AS Daily_Count
        , ROW_NUMBER() OVER (
            ORDER BY Run_Date DESC
            ) AS rn
    FROM tblUnitsOfWork
    WHERE Run_Date >= '2023-07-10'
    GROUP BY Run_Date
    ) AS d
ORDER BY Run_Date DESC
TodayRun_DateDaily_Countrndays_diff
2023-07-192023-07-15114
2023-07-192023-07-1412null
2023-07-192023-07-1313null
2023-07-192023-07-1214null
2023-07-192023-07-1115null
2023-07-192023-07-1016null

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:

, case when rn = 1 then cast(datediff(day,run_date,getdate()) as varchar(6)) else '' end as

相关问题