代码之家  ›  专栏  ›  技术社区  ›  Christopher Cass

从上一日期的特定时间到当前日期的特定时间查询SQL Server

  •  0
  • Christopher Cass  · 技术社区  · 4 年前

    很抱歉问你这个问题。我在SQL中有一个带有DateTime列的表。我需要每天运行一个脚本来显示从昨天早上8点到今天早上8点的任何台词。例如,今天我要跑:

    select *
    from Table
    Where DateTime > '2020-12-30 08:00:00.000' and DateTime < '2020-12-31 08:00:00.000'
    

    我也知道我可以运行这个,但这只会给我前一天到当前的时间:

    select *
    from Table
    Where DateTime >= DATEADD(day,-1, GETDATE()) and DateTime < GETDATE())
    

    但是,有没有一个技巧来创建脚本,这样我就可以从昨天早上8点到今天早上8点,而不必每天手动编辑脚本?

    2 回复  |  直到 4 年前
        1
  •  2
  •   GMB    4 年前

    我建议:

    select *
    from mytable
    where 
        datetime >= dateadd(hour, 8, dateadd(day, -1, convert(datetime, convert(date, getdate()))))
        and datetime < dateadd(hour, 8, convert(datetime, convert(date, getdate()))))
    
        2
  •  0
  •   sticky bit    4 年前

    你可以转换 getdate() date 然后回到 datetime 把它截短到今天00:00:00。然后使用 dateadd() 但是有几个小时。-昨天08:00:00为16,今天08:00为+8。

    SELECT *
           FROM elbat
           WHERE nmuloc >= dateadd(hour, -16, convert(datetime, convert(date, getdate())))
                 AND nmuloc < dateadd(hour, 8, convert(datetime, convert(date, getdate())));