MySQL查询按天分组时间戳

时间:2014-12-14 20:42:04

标签: mysql sql select timestamp

我有一张员工登录表,我正在尝试为员工生成本周每天工作小时数的摘要。

我的表看起来像这样:

id | user | time_in             | time_out            | break
-------------------------------------------------------------
1  | 6    | 2014-12-14 05:00:00 | 2014-12-14 07:00:00 | 15
2  | 6    | 2014-12-14 09:00:00 | 2014-12-14 14:00:00 | 30
3  | 6    | 2014-12-14 14:00:00 | 2014-12-14 20:00:00 | 0
4  | 6    | 2014-12-15 08:00:00 | 2014-12-15 11:00:00 | 15

break值以分钟为单位,因此我通过time_out - time_in - 60 * break计算当天员工的工作时数。 time_intime_out值的类型为TIMESTAMP

到目前为止,这是我的查询。似乎为null返回day,我无法弄清楚原因。

SELECT
    SUM(UNIX_TIMESTAMP(`time_out`) - UNIX_TIMESTAMP(`time_in`) - (`break` * 60)) AS `time`,
    DATE_FORMAT(FROM_UNIXTIME(`time_in`), "%Y-%m-%d") AS `day`
FROM `sign_ins`
WHERE
    `time_in` >= "2014-11-30 00:00:00" AND
    `time_out` <= "2014-12-07 00:00:00" AND
    `user` = 6
GROUP BY `day`
ORDER BY `day` ASC;

1 个答案:

答案 0 :(得分:1)

从上面的架构来看,您似乎没有为time_in和time_out字段使用时间戳。因此,查询中的更正应为..

SELECT
    SUM(UNIX_TIMESTAMP(`time_out`) - UNIX_TIMESTAMP(`time_in`) - (`break` * 60)) AS `time`,
    DATE_FORMAT(`time_in`, "%Y-%m-%d") AS `day`
FROM 
    `sign_ins`
WHERE
    `time_in` >= "2014-11-30 00:00:00" AND
    `time_out` <= "2014-12-07 00:00:00" AND
    `user` = 6
GROUP BY `day`
ORDER BY `day` ASC;

另外,我不确定你是否通过减去时间戳来获得时间差来正确使用它。它应该是......

SUM(TIMESTAMPDIFF(MINUTE, `time_out`, `time_in`) - (`break` * 60))