使用 sql 从特定日期获取前 24 小时

Get previous 24 hours from specific date using sql

我正在尝试从特定日期提取过去 24 小时。在我的 table 中,我有很多数据点,但我只想从所选 ID 提取 24 小时前的数据。这是例子

select ID, Name, FullDatetime from myTable where ID = 53 

此查询的结果如下所示:

ID   Name         FullDateime
53   John    2015-03-11 02:00:00.000

所以我想把这个日期之前的最后 24 小时拉出来。请帮忙。谢谢

我不太清楚你想要什么,你想要 24 小时或更早的记录吗?

年长者:

select ID, Name, FullDatetime from myTable 
where ID = 53 
     and dateadd(day, 1, FullDatetime) < @myDate

更年轻

select ID, Name, FullDatetime from myTable 
where ID = 53 
     and dateadd(day, 1, FullDatetime) > @myDate

如果我对你的问题理解正确,要获取 FullDateTimeValue 的最后 24 小时内具有 FullDateTime 值的记录 for ID 53,你可以使用 self加入:

    select mt1.ID, mt1.Name, mt1.FullDateTime
    from myTable mt1
        inner join myTable mt2 
            on mt1.FullDateTime between DATEADD(hour, -24, mt2.FullDateTime) and mt2.FullDateTime 
                 and mt2.ID = 53

既然你提到你有很多数据点,性能可能是一个问题。如果我们知道您在 table 上有哪些索引,也许可以编写查询以更好地使用它们。如果您在 FullDateTime 上有索引,上面的查询将使用它(在 mt1)。