在SQL中计算AM和PM

时间:2012-04-26 12:27:23

标签: sql sql-server

给出这个样本数据集:

Date_Time
10/1/2011 12:05:00 AM
10/6/2011 2:25:00 AM
10/3/2011 5:59:00 AM
10/19/2011 6:01:00 PM
11/5/2011 8:30:00 PM
11/30/2011 11:59:00 PM

SQL Server(2005或2008)中是否有可以计算这两个时间范围内记录数的日期时间函数?以下是上述数据集的结果。如果一个网站也显示这个,请告诉我。非常感谢,伙计们。

Midnight-6:00am     6:00pm – Midnight. 
3                   3

1 个答案:

答案 0 :(得分:2)

注意,您希望第二个范围到达晚上11:59,而不是午夜...使用DATEPART()获取日期的小时部分并使用汇总SUM()添加1达到每个范围的总数。所以你需要的是0到5(00:00 - 05:59)和18和23(18:00 - 23:59)之间的小时

SELECT
  SUM(CASE WHEN DATEPART(hour, Date_Time) BETWEEN 0 AND 5 THEN 1 ELSE 0 END) AS  [Midnight to 6:00am],
  SUM(CASE WHEN DATEPART(hour, Date_Time) BETWEEN 18 AND 23 THEN 1 ELSE 0 END) AS  [6:00pm to 11:59pm]
FROM your_table

更新

以上计算时间为05:59:59 am。如果这真的应该计算到06:00:00,您还需要检查6:00的各个时间部分。这可能很慢。

SELECT
  SUM(CASE WHEN
        DATEPART(hour, Date_Time) BETWEEN 0 AND 5 
        -- Look for 06:00:00 by stripping off the date portion and comparing against a character string
        OR (DATEPART(hour, Date_Time) = 6 AND DATEPART(minute, Date_Time) = 0 AND DATEPART(second, Date_Time) = 0)
      THEN 1 ELSE 0
      END
  ) AS [Midnight to 6:00am],
SUM(CASE WHEN DATEPART(hour, Date_Time) BETWEEN 18 AND 23 THEN 1 ELSE 0 END) AS  [6:00pm to 11:59pm]
FROM your_table

或者,使用

可能会更快
  SUM(CASE WHEN
        DATEPART(hour, Date_Time) BETWEEN 0 AND 5 
        -- Look for 06:00:00 also
        OR CONVERT(VARCHAR, Date_Time, 108) = '06:00:00'
      THEN 1 ELSE 0
      END
  ) AS [Midnight to 6:00am],