请注意,您希望第二个范围到晚上 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],