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:
| 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)