MYSQL查询用于计算每小时的已用时间

时间:2015-01-28 11:38:10

标签: php mysql sql

我正在尝试在MYSQL中构建一个查询来获取今天的记录,然后每小时计算出有多少记录,并且已经过了时间。

示例数据:

     Day      Time   Elapsed time
2015-01-28    9:00       0:53
2015-01-28    9:51       0:07
2015-01-28    10:32      1:45
2015-01-28    11:53      0:25

查询后的预期结果

Time  Count   Elapsed 
 7      0       0:0
 8      0       0:0
 9      2       1:00
 10     1       1:45
 11     1       0:25
 12     0       0:0
 13     0       0:0  
 14     0       0:0
 15     0       0:0
 16     0       0:0
 17     0       0:0

所以在这里我们有7到17之间的每小时和有多少记录以及那小时的经过时间。

我目前有这个查询:

SELECT  Date, 
            Count(Date) AS Count, 
            Sum(Elapsed) / 60 / 60 AS Elapsed, 
            avg(Elapsed) / 60 as average 
    FROM 
            telephone 
    WHERE 
            StartExt = 'E227'
            AND EndExt = 'E227'
            AND `Date` = CURDATE()
    Group by Date ORDER BY Date ASC

哪一天得到了全天的总数并且没有分解到每小时,我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:0)

对于有数据的所有小时,您可以使用hour()功能:

SELECT hour(time) as hour, Count(Date) AS Count, 
       Sum(Elapsed) / 60 / 60 AS Elapsed, avg(Elapsed) / 60 as average 
FROM telephone 
WHERE StartExt = 'E227' AND EndExt = 'E227' AND `Date` = CURDATE()
Group by hour(time)
ORDER BY hour ASC

如果您需要在没有通话的情况下工作数小时,则需要额外的努力。您需要一个所需时间列表,然后是left join。像这样:

SELECT h.hh as hour, Count(time) AS Count, 
       Sum(Elapsed) / 60 / 60 AS Elapsed, avg(Elapsed) / 60 as average 
FROM (select 7 as hh union all select 8 union all select 9 union all
      . . .
      select 17
     ) h left join
     telephone t
     on h.hh = hour(t.time) and
        StartExt = 'E227' AND EndExt = 'E227' AND `Date` = CURDATE()
Group by h.hh
ORDER BY h.hh ASC

请注意,WHERE条件已移至左外连接的ON子句。