开发者

SQL Server 2005 select fields from a certain time frame

开发者 https://www.devze.com 2023-03-26 13:32 出处:网络
Right now I\'m using this command to retrieve all fields from the current day: SELECT COUNT(*) FROM [SecureOrders]

Right now I'm using this command to retrieve all fields from the current day:

SELECT COUNT(*) 
FROM [SecureOrders]
WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
      AND 
      DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1)

However, I want开发者_如何学JAVA to be able to get the fields that were entered between noon yesterday and noon today - how can I go about doing that?


0.5 is noon (eg half a day)

WHERE DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), -0.5)
      AND 
      DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0.5)


DECLARE @NoonToday DATETIME;

SET @NoonToday = DATEADD(HOUR, 12, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP));

SELECT COUNT(*) FROM [SecureOrders]
WHERE [DateTime] >= DATEADD(DAY, -1, @NoonToday)
AND [DateTime] < @NoonToday;


it might seem ugly but should work

SELECT 
  COUNT(*) 
FROM 
  [SecureOrders] 
WHERE 
  DateTime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) - 0.5 AND DateTime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1) + 0.5


A variation on @Aaron Bertrand's solution, without declaring a variable and without treating a non-zero integer value as a date:

SELECT COUNT(*)
FROM SecureOrders o
  CROSS JOIN (
    SELECT DATEADD(HOUR, DATEDIFF(DAY, 0, GETDATE()) * 24 + 12, 0)
  ) AS d (TodayNoon)
WHERE o.DateTime < d.TodayNoon
  AND o.DateTime >= DATEADD(DAY, -1, d.TodayNoon)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号