Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Selecting dates where the difference is less than x in sql

I have a series of dates in a result thus (the order is important):

2020-09-24
2020-09-22
2020-09-23
2020-09-21
2020-09-17
2020-09-18
2020-09-16
2020-09-28
2020-09-25
2009-05-13
2008-10-24
2009-05-23

And I need to remove dates where there are not more than 14 days since the last used date, starting with 2020-09-24 so:

2020-09-24
2009-05-13
2008-10-24

Would be the result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve been wracking my head trying to work out how to do this but can not work out how to roll the last ‘good’ value to compare against… Is there a way in sql to do this?

>Solution :

You can use a LAG and DATEDIFF to get the number of days that have passed since the last row. Then, if you put that with a CTE (or derived table) you can then filter on that expression:

WITH CTE AS(
    SELECT V.YourColumn,
           DATEDIFF(DAY,LAG(V.YourColumn) OVER (ORDER BY V.YourColumn),V.YourColumn) AS DaysPassed
    FROM (VALUES(CONVERT(date,'20200924')),
                (CONVERT(date,'20200922')),
                (CONVERT(date,'20200923')),
                (CONVERT(date,'20200921')),
                (CONVERT(date,'20200917')),
                (CONVERT(date,'20200918')),
                (CONVERT(date,'20200916')),
                (CONVERT(date,'20200928')),
                (CONVERT(date,'20200925')),
                (CONVERT(date,'20090513')),
                (CONVERT(date,'20081024')),
                (CONVERT(date,'20090523')))V(YourColumn))
SELECT YourColumn
FROM CTE
WHERE DaysPassed IS NULL OR DaysPassed > 14; --"First" row will be NULL
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading