SQL Server 2005从特定时间范围中选择字段

时间:2011-08-08 18:44:30

标签: sql-server-2005 datetime

现在我正在使用此命令检索当天的所有字段:

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

但是,我希望能够获得昨天中午和今天中午之间输入的字段 - 我该怎么做呢?

4 个答案:

答案 0 :(得分:2)

0.5是中午(例如半天)

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

答案 1 :(得分:0)

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;

答案 2 :(得分:0)

它可能看起来很难看但应该起作用

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

答案 3 :(得分:0)

@Aaron Bertrand解决方案的变体,没有声明变量而没有将非零整数值视为日期:

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)