简体   繁体   中英

Select the last record in each group

There is a table Remark that contains data as shown below:

       SerialNo | RemarkNo  | Desp
=============================================
             10 |         1 | rainy
             10 |         2 | sunny
             11 |         1 | sunny
             11 |         2 | rainy
             11 |         3 | cloudy
             12 |         1 | rainy

If I run a query SELECT * FROM remark WHERE remark_no IN (SELECT MAX(remark_no) FROM remark GROUP BY serial_no); , I still get the above result:

What query will return the following result:

             10 |         2 | sunny
             11 |         3 | cloudy
             12 |         1 | rainy

That is, the last record in each group should be returned??

SELECT
  r1.*
FROM remark r1
  LEFT JOIN remark r2
    ON (r1.serial_no = r2.serial_no
    AND r1.remark_no < r2.remark_no)
WHERE r2.remark_no IS NULL;

For the top RemarkNo for each SerialNo (along with the other fields from the same row) :
Select all records where there isn't a higher RemarkNo for the same SerialNo

SELECT *
FROM remark r1
WHERE NOT EXISTS
  (SELECT SerialNo FROM remark r2
   WHERE (r2.RemarkNo>r1.RemarkNo)
     AND (r2.SerialNo=r1.SerialNo)
  )

http://sqlfiddle.com/#!2/7da1b/21

You can do this by returning your results and using a sort order. For example...

SELECT * from GROUP Order By GROUP.ID DESC

This will return results in the order of last record first. Then if you do not loop through results you will return only one record... the last one recorded.

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