TIMESTAMPDIFF Sum Case错误

时间:2016-12-22 17:07:48

标签: mysql

+-----------+-----------+--------+
| punchtime | punchdate | emp_id |
+-----------+-----------+--------+
| 9:51:00   | 4/1/2016  |      2 |
| 12:59:00  | 4/1/2016  |      2 |
| 10:28:00  | 4/1/2016  |      5 |
| 14:13:00  | 4/1/2016  |      5 |
| 9:56:00   | 4/1/2016  |     10 |
| 15:31:00  | 4/1/2016  |     10 |
| 10:08:00  | 5/1/2016  |      2 |
| 18:09:00  | 5/1/2016  |      2 |
| 10:15:00  | 5/1/2016  |      5 |
| 18:32:00  | 5/1/2016  |      5 |
| 10:11:00  | 6/1/2016  |      2 |
| 18:11:00  | 6/1/2016  |      2 |
| 10:25:00  | 6/1/2016  |      5 |
| 18:28:00  | 6/1/2016  |      5 |
| 10:19:00  | 6/1/2016  |     10 |
| 18:26:00  | 6/1/2016  |     10 |
+-----------+-----------+--------+

我需要计算emp_id打卡时间小于4小时的时间,并计算整体。我正在尝试下面的代码,但它不起作用。

SELECT
  a.emp_id,
  sum(  case when TIMESTAMPDIFF(hour, min(a.punchtime),
  max(a.punchtime))< 4  then 1 else 0 end  ) as 'Half Day'
FROM  machinedata a
GROUP BY
  a.emp_id

我收到错误#1111 - 无效使用群组功能

期望的输出 -

+-----------+-----------+
| emp_id    | Half Day  | 
+-----------+-----------+
|2          | 1         |
|8          | 0         | 
|10         |0          | 
+-----------+-----------+

1 个答案:

答案 0 :(得分:0)

您的数据集和所需结果不一致,所以我将忽略它......

请考虑以下内容......

请注意我提出问题的方式以及解决方案的构建。

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table 
(employee_id INT NOT NULL
,punchtime DATETIME NOT NULL
,PRIMARY KEY(employee_id,punchtime)
);

INSERT INTO my_table VALUES
( 2,'2016/01/04 09:51:00'),
( 2,'2016/01/04 12:59:00'),
( 5,'2016/01/04 10:28:00'),
( 5,'2016/01/04 14:13:00'),
(10,'2016/01/04 09:56:00'),
(10,'2016/01/04 15:31:00'),
( 2,'2016/01/05 10:08:00'),
( 2,'2016/01/05 18:09:00'),
( 5,'2016/01/05 10:15:00'),
( 5,'2016/01/05 18:32:00'),
( 2,'2016/01/06 10:11:00'),
( 2,'2016/01/06 18:11:00'),
( 5,'2016/01/06 10:25:00'),
( 5,'2016/01/06 18:28:00'),
(10,'2016/01/06 10:19:00'),
(10,'2016/01/06 18:26:00');

SELECT employee_id
     , SUM(diff < 14400 ) half
  FROM 
     ( SELECT x.*
             , DATE(x.punchtime) dt
             , TIME_TO_SEC(MAX(y.punchtime)) - TIME_TO_SEC(MIN(x.punchtime)) diff
          FROM my_table x 
          JOIN my_table y 
            ON y.employee_id = x.employee_id
           AND DATE(y.punchtime) = DATE(x.punchtime)
         GROUP
            BY x.employee_id
             , dt
      ) n
  GROUP
     BY employee_id;
+-------------+------+
| employee_id | half |
+-------------+------+
|           2 |    1 |
|           5 |    1 |
|          10 |    0 |
+-------------+------+