从当前日期时间减去小时数并与数据类型为 datetime 的列值进行比较

发布于 2025-01-15 09:20:50 字数 956 浏览 4 评论 0原文

我想要过去一小时内添加到表中的所有 MAFN 列值 (:mm)。 ReturnDt 列存储以 DateTime 格式添加的时间,例如'2005-01-11 08:50:24.767'

我可以获取 ReturnDt 的小时数并获取当前时间(在两个单独的查询中)。

SELECT  ReturnDt, 
       DATEPART(hour, ReturnDt) As 
FROM [Sidney].[dbo].[LibraryTransactions]

SELECT GETDATE() 'Today', DATEPART(hh,GETDATE()) 'Hour Part'

由于显而易见的原因,这还不够。 首先,SELECT GETDATE()... 不能用作子查询。 其次,我似乎无法从 SELECT GETDATE() 查询的结果中减去 1 小时。 第三,即使上述两者以某种方式起作用,查询也会将时间减少到几个小时,并且不考虑日期。

我正在使用 SQl Server 2005

提前致谢!

编辑:

表格如下所示: 输入图片此处描述

预期结果:如果我今天(2022 年 3 月 18 日)16:00 运行查询,我应该只会得到这些值 输入图片此处描述

I want all the MAFN column values that were added to the table in the last hour(:mm). The column ReturnDt stores the time it was added in DateTime format ex.'2005-01-11 08:50:24.767'

I can get the hours for ReturnDt and get the current hour(in two separate queries).

SELECT  ReturnDt, 
       DATEPART(hour, ReturnDt) As 
FROM [Sidney].[dbo].[LibraryTransactions]

And

SELECT GETDATE() 'Today', DATEPART(hh,GETDATE()) 'Hour Part'

But this is not enough for obvious reasons.
Firstly SELECT GETDATE()... doesn't work as a subquery.
Secondly, I can't seem to subtract 1 hour from the result of the SELECT GETDATE() query.
Thirdly, even if the above two somehow worked, the queries reduce time to hours and it doesn't take into account the date.

I am using SQl Server 2005

Thanks in advance!

Edit:

The table looks like:
enter image description here

Expected Result: If I ran the query today(18 Mar 2022) at 16:00 hours I should only get these values
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对岸观火 2025-01-22 09:20:51

一个小技巧...

将其放入您的 where caluse 中:
(column > getdate() - (1.0/24) AND column < getdate() - (2.0/24))

示例:(表 'sometable' 包含名为 'datecolumn' 的日期时间列)

select * from sometable
其中 (datecolumn > getdate() - (1.0/24) AND datecolumn < getdate() - (2.0/24))

...将为您提供某个表中“现在”1 到 2 小时老亲戚的记录。

A little trick...

Put this in your where caluse:
(column > getdate() - (1.0/24) AND column < getdate() - (2.0/24))

Example: (table 'sometable' contains a datetime column named 'datecolumn')

select * from sometable
where (datecolumn > getdate() - (1.0/24) AND datecolumn < getdate() - (2.0/24))

...will give you records in sometable who are between 1 and 2 hrs old relative "now".

Oo萌小芽oO 2025-01-22 09:20:50

DateDiff() 怎么样

where
   DateDiff( hour, ReturnDT, getdate() ) > 1

How about DateDiff()

where
   DateDiff( hour, ReturnDT, getdate() ) > 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文