简体   繁体   中英

SQL query to retrieve a row with the highest possible ID

I have the following data:

ID  Value
1   X
2   Y
3   Y
4   X
5   X
6   Y

How to retrieve the row where Value = "X" and ID is the highest possible? (in that case it would be the 5th row)

SELECT
     Value
    ,MAX(ID) HighestID
FROM
    table
WHERE
    Value = 'X'
GROUP BY
    Value
SELECT TOP 1 ID, Value
FROM table
WHERE Value = 'X'
ORDER BY ID DESC

Or another way (this works as you already know the value you want):

SELECT MAX(ID), 'X' AS Value
FROM table
WHERE Valud = 'X'

从tableName中选择Top 1 *,其中value ='X'由ID Desc排序

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