I have a query which returns ID, effectiveDate, and many other columns. Now I need to filter this result to get the records that are upto 2 years old from the most recent effectivedate for each ID.
Table has data similar to the following
ID | EffectiveDate | Col3 | Col4 | ........
____________________________________________________________
1 | 2020-09-30 |
1 | 2019-09-30 |
1 | 2018-09-30 |
1 | 2018-03-31 |
1 | 2017-09-30 |
2 | 2019-03-31 |
2 | 2018-03-31 |
2 | 2017-03-31 |
3 | 2015-06-30 |
3 | 2015-03-31 |
3 | 2014-12-31 |
3 | 2012-06-30 |
I want the output to be
ID | EffectiveDate | Col3 Col4 ........
____________________________________________________________
1 | 2020-09-30 |
1 | 2019-09-30 |
1 | 2018-09-30 |
2 | 2019-03-31 |
2 | 2018-03-31 |
2 | 2017-03-31 |
3 | 2015-06-30 |
3 | 2015-03-31 |
3 | 2014-12-31 |
I have tried the following
select A.* from table A
inner join
(select ID, col3, col4, max(effectivedate) as MaxDate
from table A
group by ID, col3, Col4 ) B
on A.ID = B.ID
where (B.Maxdate - A.effectiveDate) < 740;
but this query returns all the records, not filtering anything. Also this is throwing a cross join result. Please help!
Use window functions. Your text specifies the maximum for each
id
:(Note:
730
would make more sense.)If you want this by
id
/col3
/col4
as the query suggests then use all three in thepartition by
.