用于从特定列的上次访问中获取数据的SQL查询

时间:2015-05-14 09:03:35

标签: sql

我有一个表格,其中列是regno,dt,visitno和symptom_code。我想从上次访问regno获取数据。请建议SQL查询。

1 个答案:

答案 0 :(得分:2)

每个DBMS都支持:

SELECT *
FROM tab AS t1
WHERE dt =
 ( SELECT MAX(dt) FROM tab AS t2
   WHERE t1.regno = t2.regno)

大多数DBMS支持窗口化聚合函数,更容易编写,通常更有效:

SELECT *
FROM 
 ( SELECT ...
     ,RANK() 
      OVER (PARTITION BY regno
            ORDER BY dt DESC) AS rnk
    FROM tab
 ) AS dt
WHERE rnk = 1