3

我正在构建一个非常简单的应用程序,我可以在其中“打卡”各种任务,为此我在 MySQL 中有一个如下所示的数据库表:

|ID|user_id |task_id|checkin_time       |checkout_time
------------------------------------------------------------
|31|2       |289    |2012-07-12 09:50:03|2012-07-12 09:51:27
|32|2       |289    |2012-07-12 10:00:05|2012-07-12 13:00:05

我想通过 SQL 查询从中得到的是上周用户每天签入的总时间。我试过这个查询:

SELECT COUNT( id ) AS time_id, SUM( checkout_time - checkin_time ) AS total_time, DATE( checkout_time ) AS checkout_day
FROM time_table
WHERE user_id =  '2'
AND checkout_time >= ( DATE_SUB( CURDATE( ) , INTERVAL 1 WEEK ) ) 
GROUP BY checkout_day
ORDER BY checkout_day ASC

这给出了一个非常好的结果,但是如果一天有多个“签入”会出现一些严重的并发症——比如SUM( checkout_time - checkin_time )第一个 checkin_time 和最后一个 checkout_time——这并不一定代表用户签入的时间(除非他 100% 的时间都被检查过)。

我想要的是让 SUM() 获取每个总和,然后将它们每天加起来。

关于我如何解决这个问题的任何想法?

4

2 回答 2

2

使用子查询获取时间差,然后求和:

SELECT 
  COUNT( id ) AS time_id, 
  SUM( time_diff ) AS total_time, 
  DATE( checkout_time ) AS checkout_day
FROM (
  select 
    id, 
    checkout_time - checkin_time as time_diff, 
    checkout_time
  from time_table)
WHERE user_id =  '2'
AND checkout_time >= ( DATE_SUB( CURDATE( ) , INTERVAL 1 WEEK ) ) 
GROUP BY checkout_day
ORDER BY checkout_day ASC
于 2012-07-19T07:04:01.997 回答
1

试试这个:

“天”的区别:

SELECT COUNT( id ) AS time_id, SUM( TO_DAYS(checkout_time) - TO_DAYS(checkin_time) ) AS total_time, DATE( checkout_time ) AS checkout_day
FROM time_table
WHERE user_id =  '2'
AND checkout_time >= ( DATE_SUB( CURDATE( ) , INTERVAL 1 WEEK ) ) 
GROUP BY checkout_day
ORDER BY checkout_day ASC

“秒”的区别:

SELECT COUNT( id ) AS time_id, SUM( UNIX_TIMESTAMP(checkout_time) - UNIX_TIMESTAMP(checkin_time) ) AS total_time, DATE( checkout_time ) AS checkout_day
    FROM time_table
    WHERE user_id =  '2'
    AND checkout_time >= ( DATE_SUB( CURDATE( ) , INTERVAL 1 WEEK ) ) 
    GROUP BY checkout_day
    ORDER BY checkout_day ASC
于 2012-07-19T07:14:16.407 回答