简体   繁体   中英

SQL query to fetch data from last visit of particular column

I have a table where columns are regno,dt,visitno and symptom_code. I'd like to fetch data from last visit of regno. Please suggest SQL query.

Every DBMS supports this:

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

Most DBMSes support Windowed Aggregate Functions, easier to write and usually more efficient:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM