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

If a multi row account has a row in a specified date range, how to select all previous rows for that account before that date?

Say I have a table that looks like the following:

Account Sale Date
A $5 2023-Jan-01
A $8 2023-Feb-15
B $2 2023-Mar-03
A $7 2023-Apr-10
A $9 2024-Jan-01

If a user selects a date range of 2023-Apr-01 to 2023-Apr-30 I would want the table to filter down to the below:

Account Sale Date
A $5 2023-Jan-01
A $8 2023-Feb-15
A $7 2023-Apr-10

Where I can not only see the account within that specified date range, but also all previous sales on that account before the specified date range. Simply doing SELECT * WHERE Date < 2023-Apr-30 would return:

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

Account Sale Date
A $5 2023-Jan-01
A $8 2023-Feb-15
B $2 2023-Mar-03
A $7 2023-Apr-10

Which is not the desired result. I initially did a partition like MAX(Date) OVER (PARTITION BY Account ORDER BY Date) AS Max_Date:

Account Sale Date Max_Date
A $5 2023-Jan-01 2024-Jan-01
A $8 2023-Feb-15 2024-Jan-01
B $2 2023-Mar-03 2023-Mar-03
A $7 2023-Apr-10 2024-Jan-01
A $9 2024-Jan-01 2024-Jan-01

and did SELECT * WHERE Max_Date < 2023-Apr-30 which would work if the max sale date for A was 2023-Apr-30 but because it is 2024-Jan-01 the result would be an empty table. Any ideas?

>Solution :

Seems you want an EXISTS with a correlated subquery:

SELECT YT.Account,
       YT.Sale,
       YT.Date
FROM dbo.YourTable YT
WHERE EXISTS (SELECT 1
              FROM dbo.YourTable E
              WHERE E.Account = YT.Account
                AND E.Date >= @StartDate
                AND E.Date <= @EndDate); --If date is actually a date and time value you will want:
                                         --E.Date < DATEADD(DAY, 1, @EndDate)
             
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