SQL:如何从返回的多个记录中选择最高PK(SQL: How to select highest PK out of multiple records returned)

编程入门 行业动态 更新时间:2024-10-28 11:23:23
SQL:如何从返回的多个记录中选择最高PK(SQL: How to select highest PK out of multiple records returned)

我有一个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 DESC

Note that the WHERE clause is not necessary here since we are ordering by Entry_Date already.

更多推荐

本文发布于:2023-08-04 16:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417452.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   select   PK   SQL   records

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!