【问题标题】:Select all records with max DateTime using where clause使用 where 子句选择具有最大 DateTime 的所有记录
【发布时间】:2018-07-12 23:56:35
【问题描述】:

我是 SQL Server 2008 Express 的新手。

我有一个名为Table1 的表,其中有First_NameOrder_Date_Time 列。

我想要一个 SQL 查询,它可以选择 First_Name = Alex 和最大 Order_Date_Time 的所有记录。该表包含多个日期完全相同的日期。

有人知道怎么做吗?

【问题讨论】:

  • 这真的与C#无关,如果你只是在寻找一个SQL查询
  • 你期待什么输出?您只想要 Alex 的最大 Order_Date_Time 吗?就像在单个值中一样?
  • 汤姆·迪。我想要 First_Name = "Alex" 和最大日期时间的所有记录。我将结果保存在 DataTable 中

标签: sql sql-server


【解决方案1】:

这应该会给你正确的结果,并且非常简洁。

SELECT *
FROM Table1
WHERE Order_Date_Time = (select MAX(Order_Date_Time) FROM Table1) and First_name = 'Alex'

【讨论】:

  • 感谢您的回答,但此查询仅返回一条记录。假设我在数据库中有 1000 条记录。我有 10 条记录,其中包含 Alex 和最大日期,这 10 条记录具有确切的日期。我想选择那 10 条记录
  • 您是否有多个相同日期的最大日期?因为您的问题说您想要名称为 alex 的最大日期,所以通常您只会返回 1 条记录。您也可以尝试:Select * from Table1 where First_Name = 'Alex'
  • 是的,我有多个日期完全相同的日期。你能修改答案吗? tnx
【解决方案2】:

在正确的索引下具有良好性能的一种简单方法是:

select t1.*
from table1 t1
where t1.order_date_time = (select max(tt1.order_date_time) from table1 tt1 where tt1.first_name = t1.first_name);

table1(name, order_date_time) 中的正确索引。

【讨论】:

    【解决方案3】:

    你可以使用row_number()函数:

    select top (1) with ties t1.*
    from table1 t1
    where t1.First_Name = 'Alex'
    order by row_number() over(partition by t1.first_name order by t1.order_date_time desc);
    

    【讨论】:

    • 抱歉 t1 是什么?
    • @Sam。 . . t1 是表别名,table1 是表名,需要替换为您的表名。
    【解决方案4】:

    这将给出所有包含 Alex 的记录。这似乎是您从评论中看到的内容。

    SELECT First_Name, Order_Date_Time
    FROM Table1
    WHERE First_Name = 'Alex'
    

    【讨论】:

    • 没有。这只会返回包含所有可用记录的两列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2023-04-01
    • 2013-10-25
    • 2016-01-27
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多