sql中的DateTime只比较时间

时间:2015-01-20 14:14:46

标签: sql-server

ID                  DateTime                 Code
----------          --------------           ----------
58                  2015-01-01 20:00:00      1111
58                  2015-01-11 10:00:00      8523
58                  2015-01-11 03:00:00      4555
58                  2015-01-19 00:01:00      8888
 9                  2015-01-01 20:00:00      4444

如何计算特定ID的代码数量,忽略它的日期,但必须在20:00:00到06:00:00之间

select count(code) as count from table 1 where ID='58' and DateTime between '20:00:00' and '06:00:00'

预期输出为

计数

3

3 个答案:

答案 0 :(得分:2)

SELECT count(code) as count 
FROM table1 
WHERE 
  ID='58' and 
  (CAST(DateTime as time) >= '20:00' 
   or CAST(DateTime as time) <= '06:00')
编辑:约翰,我理解这个问题。以下是处理这些案例的完整解决方案:

为了使用变量:

DECLARE @HourBegin time = '07:00'
DECLARE @HourEnd   time = '17:30'

    SELECT count(code) as count 
    FROM table1 
    WHERE 
      ID='58' and 
      (CAST(DateTime as time) between @HourBegin and @HourEnd or
       ((CAST(DateTime as time) <= @HourEnd or 
        CAST(DateTime as time) >= @HourBegin) and 
           @HourBegin > @HourEnd)
       )

答案 1 :(得分:0)

与之前的答案几乎相同,但有几个小时它对我来说看起来更好,可能你需要DISTINCT代码

SELECT count(DISTINCT  code) as count 
FROM table1 
WHERE 
  ID='58' and 
  (DATEPART(HOUR,DateTime) >= 20 
   or DATEPART(HOUR,DateTime) < 6)

更新:从&lt; = 6更改为&lt; 6

答案 2 :(得分:-1)

<强>更新

此答案适用于MySQL 当我开始撰写答案时,问题被标记为mysqlsql-server。 OP同时编辑了它。


此查询应该在MySQL上执行您想要的操作。

SELECT count(code) AS `count` 
FROM `table 1`
WHERE ID='58' 
  AND TIME(`DateTime`) NOT BETWEEN '06:00:01' AND '19:59:59'

MySQL函数TIME()仅从DATETIME值中提取时间分量。

在5.7版本上,MySQL在DATETIME列上添加了support for fractional seconds(最多6位数)。上述查询将包括时间大于06:00:00但小于06:00:01的条目(在上午6点之后的第一秒内发生的事件)。

对于MySQL 5.7及更高版本,正确的查询是:

SELECT count(code) AS `count` 
FROM `table 1`
WHERE ID='58' 
  AND (TIME(`DateTime`) <= '06:00:00' OR '20:00:00' <= TIME(`DateTime`))

我不了解SQL Server