我们有具有以下数据和结构的表 T
__________________________
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|
____|________|____________|
给定@date_from = '2007-01-01'
并@date_to = '2008-06-01'
编写一个查询,该查询返回 @date_from 到 @date_to 的过滤子集的最大记录。
结果应如下所示:
__________________________
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|
____|________|____________|
一种可能的解决方案是:
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
所以你知道一个更好/更快的方法来做到这一点。
谢谢。