1

给定这个样本数据集:

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
4

1 回答 1

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。如果这真的应该算到 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],
于 2012-04-26T12:35:18.163 回答