We have the table T with the following data and structure
__________________________
ID | Grp | Dt |
____|________|____________|
1 | A | 2007-11-22|
2 | A | 2008-01-03|
3 | A | 2008-01-03|
4 | A | 2011-04-13|
5 | B | 2007-11-22|
6 | B | 2010-04-28|
7 | B | 2009-03-19|
8 | B | 2007-11-22|
9 | C | 2010-04-28|
10 | C | 2009-03-19|
11 | C | 2011-04-13|
12 | C | 2012-02-22|
13 | D | 2007-11-22|
14 | D | 2010-04-28|
15 | D | 2009-03-19|
16 | E | 2007-11-22|
17 | E | 2010-04-28|
18 | E | 2011-04-13|
19 | F | 2007-11-22|
20 | G | 2007-11-22|
21 | H | 2007-11-22|
22 | H | 2010-04-28|
23 | H | 2009-03-19|
24 | H | 2008-03-15|
____|________|____________|
Given @date_from = '2007-01-01'
and @date_to = '2008-06-01'
write a query that returns the max records of the filtered subset of @date_from to @date_to.
The result should be as follows:
__________________________
ID | Grp | Dt |
____|________|____________|
2 | A | 2008-01-03|
3 | A | 2008-01-03|
5 | B | 2007-11-22|
8 | B | 2007-11-22|
13 | D | 2007-11-22|
16 | E | 2007-11-22|
19 | F | 2007-11-22|
20 | G | 2007-11-22|
21 | H | 2008-03-05|
____|________|____________|
One possible solution is:
DECLARE @date_from AS DATE = '2007-01-01'
DECLARE @date_to AS DATE = '2008-06-01'
WITH TFltr AS ( SELECT ID, Grp, Dt FROM T WHERE @date_from <= Dt AND Dt <= @date_to )
SELECT t1.ID, t1.Grp, t1.Dt
FROM TFltr t1
LEFT OUTER JOIN TFltr t2 ON t1.Grp = t2.Grp AND t1.Dt < t2.Dt
WHERE t2.ID IS NULL
So do you know of a better/faster aproach to do this.
Thanks.