在mysql中按时间范围查询分组会产生错误

时间:2011-12-10 01:51:42

标签: mysql sql

我使用以下查询来获取基于时间范围的计数。从创建的时间中减去currentntime但产生错误

  

错误代码1064,SQL状态42000:您的SQL中有错误   句法;查看与MySQL服务器版本对应的手册   在'TO 8然后'8Hrs'附近使用正确的语法           轮次时(time_to_sec(timediff(now(),第4行的`created_date_t'

SELECT t.range, count(*) as num
FROM (
SELECT CASE
    WHEN round(time_to_sec(timediff(now() , `created_date_time`))/3600) BETWEEN 0 TO 8 then '8Hrs'
    WHEN round(time_to_sec(timediff(now() , `created_date_time`))/3600) BETWEEN 9 TO 16 then '16Hrs'
    WHEN round(time_to_sec(timediff(now() , `created_date_time`))/3600) BETWEEN 17 TO 24 then '24Hrs'
    WHEN round(time_to_sec(timediff(now() , `created_date_time`))/3600) > 24 then 'G24Hrs'
    AS range
    FROM `ticket`
)  as t     
GROUP BY range

我必须避免重复

round(time_to_sec(timediff(now() , created_date_time))/3600)   

语句。

表结构

id  created_date_time   issue   
-------------------------------------
1   2011-12-07 05:29:28 test  
2   2011-12-08 07:56:15 test  
3   2011-12-08 05:56:15 test  

创建查询

CREATE TABLE `ticketingsystem`.`ticket` (
`id` bigint( 20 ) NOT NULL AUTO_INCREMENT ,
`created_date_time` datetime NOT NULL ,
`issue` text NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM DEFAULT CHARSET = latin1   

我想要低于输出

这些字段中没有记录创建记录后的待定时间

8hrs    16hrs   24hrs   >24hr
---------------------------------
3       2        6      4

2 个答案:

答案 0 :(得分:3)

你的查询中有很多错误,所以我改写了所有错误。

首先,我建议你创建一个VIEW。这是一次性事情。

CREATE VIEW ticket_wait AS
  SELECT HOUR(TIMEDIFF(NOW(), created_date_time)) AS hdiff
  FROM ticket;

在此之后,您可以使用以下查询来获得结果。

SELECT COUNT(hdiff) count,
  CASE
    WHEN hdiff BETWEEN 0 AND 8 THEN '8Hrs'
    WHEN hdiff BETWEEN 9 AND 16 THEN '16Hrs'
    WHEN hdiff BETWEEN 17 AND 24 THEN '24Hrs'
  ELSE '>24Hrs'
END `range`
FROM ticket_wait
GROUP BY `range`

在表格上使用上述查询

+----+---------------------+-------+
| id | created_date_time   | issue |
+----+---------------------+-------+
|  1 | 2011-12-10 07:06:44 | foo   |
|  2 | 2011-12-08 04:29:28 | foo   |
|  3 | 2011-12-08 23:29:28 | foo   |
|  4 | 2011-12-08 14:29:28 | foo   |
|  5 | 2011-12-09 12:29:28 | foo   |
|  6 | 2011-12-09 17:29:28 | foo   |
|  7 | 2011-12-09 23:29:28 | foo   |
|  8 | 2011-12-10 06:29:28 | foo   |
|  9 | 2011-12-10 04:29:28 | foo   |
| 10 | 2011-12-10 01:29:28 | foo   |
+----+---------------------+-------+

您的输出将是

+-------+--------+
| count | range  |
+-------+--------+
|     1 | 16Hrs  |
|     1 | 24Hrs  |
|     5 | 8Hrs   |
|     3 | G24Hrs |
+-------+--------+

答案 1 :(得分:2)

除了克里斯蒂安关于BETWEEN X AND Y的观察之外,你错过了END陈述中的CASE

SELECT CASE
    WHEN ...
    WHEN ...
END AS `RANGE` -- Note the END!
FROM ...