在MySQL中每行使用SUM()

时间:2012-07-19 06:58:42

标签: mysql sql database

我正在构建一个非常简单的应用程序,我可以“查看”各种任务,为此我在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()获取每个总和,然后每天添加它们。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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