当max在其他列上时获取id值

时间:2012-08-24 14:37:04

标签: sql sql-server

这是获取最近日期的id值的最佳方法吗?

table1
id,entrydate
1,8/23/2012
2,8/24/2012
3,8/23/2012

select id from table1 where entrydate = ( select MAX(entrydate) from table1 )

5 个答案:

答案 0 :(得分:1)

你已经有了一个好方法。我要注意关系:

select top id from table1 where entrydate = ( select MAX(entrydate) from table1 )

当然,这是假设您使用的是SQL Server。

答案 1 :(得分:1)

假设您正在使用SQL-Server,您可以使用ORDER BY,然后选择一行:

SELECT TOP 1 id
FROM table
ORDER BY entrydate DESC

在MySql中,它是LIMIT

SELECT id
FROM table
ORDER BY entrydate DESC
LIMIT 1

在Oracle中:

SELECT id
FROM (SELECT id FROM table ORDER BY entrydate DESC) 
WHERE ROWNUM = 1

答案 2 :(得分:0)

SELECT id FROM table1 ORDER BY entrydate DESC LIMIT 1

答案 3 :(得分:0)

您应该能够SELECT id FROM table1 ORDER BY entrydate DESC LIMIT 1

答案 4 :(得分:0)

不完全是,你想这样做:

对于SQL Server:

SELECT TOP 1 id, MAX(entrydate) FROM table1 GROUP BY id

对于MySQL:

SELECT id, MAX(entrydate) FROM table1 GROUP BY id LIMIT 1
相关问题