选择最近的检查

时间:2017-10-21 15:54:54

标签: sql date ms-access select greatest-n-per-group

我有一个ROAD_INSPECTION表:

+----+------------------------+-----------+
| ID |          DATE          | CONDITION |
+----+------------------------+-----------+
|  1 | 01/01/2009             |        20 |
|  1 | 05/01/2013             |        16 |
|  1 | 04/29/2016 10:02:52 AM |        15 |
+----+------------------------+-----------+
|  2 | 01/01/2009             |         8 |
|  2 | 06/06/2012 9:55:13 AM  |         8 |
|  2 | 04/28/2015             |        11 |
+----+------------------------+-----------+
|  3 | 06/11/2012             |        10 |
|  3 | 04/21/2015             |        19 |
+----+------------------------+-----------+

选择最近一次检查的最有效方法是什么?该查询需要包含IDCONDITION列,尽管它们不会干净地group by

+----+------------------------+-----------+
| ID |          DATE          | CONDITION |
+----+------------------------+-----------+
|  1 | 04/29/2016 10:02:52 AM |        15 |
+----+------------------------+-----------+
|  2 | 04/28/2015             |        11 |
+----+------------------------+-----------+
|  3 | 04/21/2015             |        19 |
+----+------------------------+-----------+

1 个答案:

答案 0 :(得分:1)

一种方法是在派生表中检索iddate列,并将输出连接到主表,以便从condition列检索相应的数据,如下所示。

SELECT t1.id,
       t1.date1,
       t2.CONDITION1
FROM
  (SELECT id,
          max(date1) AS date1
   FROM table1
   GROUP BY id) t1
JOIN table1 t2 ON t1.id = t2.id
AND t1.date1 = t2.date1;

<强>结果:

id  date1                  CONDITION1
-------------------------------------
1   29.04.2016 10:02:52    15
2   28.04.2015 00:00:00    11
3   21.04.2015 00:00:00    19

<强> DEMO

如果您的rdbms支持Windows功能,请使用以下内容。

SELECT id, 
       date1, 
       condition1
FROM
  (SELECT id,
          date1,
          condition1,
          row_number() over(PARTITION BY id
                            ORDER BY date1 DESC) AS rn
   FROM table1 ) t1
WHERE rn = 1;

<强> DEMO