我有一个表格,其中列是regno,dt,visitno和symptom_code。我想从上次访问regno获取数据。请建议SQL查询。
答案 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