我有一个Journal_Entry表,主键为Journal_Entry_ID,(以及其他列)是一个Entry_Date列。
我正在尝试通过SELECT MAX(Entry_Date)进行SELECT MAX(Entry_Date)最近的Entry_Date的查询 - 但问题是用户可能在给定日期记录了多个条目。 因此,如果用户今天两次记录日记条目,则此SELECT语句可能返回多行,因为已多次记录相同的MAX Entry_Date。
所以我想要做的是,如果SELECT MAX语句返回多个记录,请选择具有最高返回值的Journal_Entry_ID的记录。
现在我的查询看起来像这样:
SELECT Journal_Entry_ID, Entry_Date FROM Journal_Entry WHERE Entry_Date = (SELECT MAX(Entry_Date) FROM Journal_Entry);我正在使用SQL SERVER。 任何帮助将不胜感激。
谢谢。
编辑:我正在使用SQL SERVER。 不像我最初报道的那样是我的SQL。
I have a Journal_Entry table, with a Primary Key of Journal_Entry_ID, and (among other columns) an Entry_Date column.
I'm trying to do a query that selects the most recent Entry_Date -- via a SELECT MAX(Entry_Date) -- but the problem is that the user may have logged more than one entry on a given date. So if the user logged a journal entry twice today, this SELECT statement could return more than one row because the same MAX Entry_Date has been logged more than once.
So what I'd like to do is, if the SELECT MAX statement returns more than one record, choose the record that has the highest Journal_Entry_ID of the ones returned.
Right now my query looks like this:
SELECT Journal_Entry_ID, Entry_Date FROM Journal_Entry WHERE Entry_Date = (SELECT MAX(Entry_Date) FROM Journal_Entry);I'm using SQL SERVER. Any help would be greatly appreciated.
Thanks.
EDIT: I'm using SQL SERVER. Not My SQL as I had originally reported.
最满意答案
SELECT TOP 1 Journal_Entry_ID, Entry_Date FROM Journal_Entry ORDER BY Entry_Date DESC, Journal_Entry_ID DESC请注意,这里不需要WHERE子句,因为我们已经通过Entry_Date进行排序。
SELECT TOP 1 Journal_Entry_ID, Entry_Date FROM Journal_Entry ORDER BY Entry_Date DESC, Journal_Entry_ID DESCNote that the WHERE clause is not necessary here since we are ordering by Entry_Date already.
更多推荐
发布评论