Get last distinct set of records

后端 未结 5 651
既然无缘
既然无缘 2020-12-08 00:06

I have a database table containing the following columns:

id   code   value   datetime   timestamp

In this table the only unique values res

5条回答
  •  暖寄归人
    2020-12-08 01:07

    This should work for you.

     SELECT * 
     FROM [tableName] 
     WHERE id IN (SELECT MAX(id) FROM [tableName] GROUP BY code)
    

    If id is AUTO_INCREMENT, there's no need to worry about the datetime which is far more expensive to compute, as the most recent datetime will also have the highest id.

    Update: From a performance standpoint, make sure the id and code columns are indexed when dealing with a large number of records. If id is the primary key, this is built in, but you may need to add a non-clustered index covering code and id.

提交回复
热议问题