DATEADD() 函数查找本工作日的值

发布于 2024-11-25 09:25:57 字数 567 浏览 4 评论 0原文

如何使用 SQL DATEADD() 函数查找该工作日的记录?例如:

SELECT * FROM records r
WHERE r.creationTime <= GETDATE()
  AND r.creationTime >= DATEADD(dd, -1 * hoursFromStartOfThisDay, GETDATE())

其中“hoursFromStartOfThisDay”正是它所说的。

注意:我说的是工作日,所以周一至周五上午 9 点至下午 5 点(如果有的话)。

谢谢你们!

编辑:我还希望在周/月的开始甚至小时的开始时应用一个解决方案。

编辑:因此,如果一条记录是在 18/07/2011 08:55:00 创建的,另一条记录是在 18/07/2011 09:05:00 创建的,我希望查询选取第二条记录,而不是第一条记录。但是,如果当前的 GETDATE() 是 18/07/2011 09:15:00 那么事情就会变得棘手。

添加 AND r.creationTime >= '9am' 怎么样?

How can I use the SQL DATEADD() function to find a record from this business day? For example:

SELECT * FROM records r
WHERE r.creationTime <= GETDATE()
  AND r.creationTime >= DATEADD(dd, -1 * hoursFromStartOfThisDay, GETDATE())

Where 'hoursFromStartOfThisDay' is exactly what it says.

Note: I'm talking about business days so from 9am-5pm, Monday-Friday if that matters at all.

Thanks, guys!

Edit: I am also looking to apply a solution to this for the start of the beginning of the week/month and maybe hour too.

Edit: So if a record was created at 18/07/2011 08:55:00 and another created at 18/07/2011 09:05:00, I want the second record to be picked up by the query and not the first. However if the current GETDATE() is 18/07/2011 09:15:00 then it gets tricky.

how about adding AND r.creationTime >= '9am'?

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

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

发布评论

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

评论(1

眼眸里的快感 2024-12-02 09:25:57

您真的需要一个 hoursFromStartOfThisDay 变量吗?
如果您的一天是固定的,从 9 点到 5 点,您可以使用以下静态范围:

-- cache current date to avoid multiple calls
DECLARE @startOfADay INT
DECLARE @dayLength INT
DECLARE @currentDate DATETIME
SET @currentDate = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
SET @startOfADay = 9
SET @dayLength = 8

SELECT 
   ...
FROM
   ...
WHERE ...
BETWEEN 
      DATEADD(hh, @startOfADay, @currentDate) 
      AND 
      DATEADD(hh, @startOfADay + @dayLength, @currentDate)

Are you really need a hoursFromStartOfThisDay variable?
If your day is static, from 9 to 5, you can use just this static range:

-- cache current date to avoid multiple calls
DECLARE @startOfADay INT
DECLARE @dayLength INT
DECLARE @currentDate DATETIME
SET @currentDate = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
SET @startOfADay = 9
SET @dayLength = 8

SELECT 
   ...
FROM
   ...
WHERE ...
BETWEEN 
      DATEADD(hh, @startOfADay, @currentDate) 
      AND 
      DATEADD(hh, @startOfADay + @dayLength, @currentDate)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文