计算持续时间百分比

时间:2015-07-21 02:27:55

标签: mysql sql

我有一个表,只要状态发生变化就会记录网站的HTTP状态代码,所以表格看起来像这样......

id    status                   date
-----------------------------------
1     404       2015-10-01 13:30:00
2     200       2015-10-02 13:30:00
3     404       2015-10-03 13:30:00

我想使用这些数据在我的网站上显示一个表格,显示每个状态记录的次数以及状态持续时间到当前时间。

我已成功设法使用以下查询获取每个状态的总计数....

SELECT 
   `status`, 
   COUNT(*) AS `status_count` 
FROM `table_name` 
GROUP BY `status` 
ORDER BY `status`

......执行时给我这样的东西......

status    status_count
----------------------
200       1
404       2

我想修改我的sql添加持续时间到我的日期列计算的结果,我的目标是最终得到这个......

status    status_count    duration (%)
-----------------------------------
200       1              20
404       2              80

3 个答案:

答案 0 :(得分:2)

这是SQL FIDDLE DEMO

SELECT t1.status
      ,COUNT(t1.id) as status_count
      ,SUM(IF(t2.date IS NULL, NOW(), t2.date)-t1.date) / (NOW()-t3.start_date) as duration
  FROM table_name t1
       LEFT JOIN table_name t2 ON t1.id = (t2.id - 1)
      ,(SELECT MIN(date) as start_date FROM table_name) t3
GROUP BY t1.status

答案 1 :(得分:1)

我比尼克更复杂但却给出了不同的结果 我在excel上尝试验证值是否正确。

我使用2015-07-01 13:30:00开始约会,因此NOW()功能可以正常工作

这意味着秒数

404 | 86400    1 day   | 0.05101 
200 | 86400    1 day   | 0.05101   
404 | 1521138 17 days  | 0.89799 
total 1693938

最终结果

404 | 2 | 0.94899 
200 | 1 | 0.05101   

SQL FIDDLE DEMO

SELECT  status, Count(status), SUM(secdiff) / MAX(sectotal) as porcentage
FROM
(
    SELECT 
         h1.status, 
         h2.dateupdate d1, 
         h1.dateupdate d2,
         TIMESTAMPDIFF(SECOND,h1.dateupdate, h2.dateupdate) secdiff,
         TIMESTAMPDIFF(SECOND,
                       (SELECT MIN(dateupdate) from logHttp), 
                       NOW()) sectotal
    FROM 
        logHttp as h1 INNER JOIN
        (
          (Select * from logHttp)
          union
          (select MAX(id) +1, 0, NOW() from logHttp)
        ) as h2
        On h1.id + 1 = h2.id     
 ) as t1
 group by status;

答案 2 :(得分:0)

使用此查询

select a.*,(a.status_count/b.tot)*100 as duration_per from (SELECT 
       `status`, 
       COUNT(*) AS `status_count` 
    FROM `table_name` 
    GROUP BY `status` 
    ORDER BY `status`) a join (select count(*) as tot from `table_name`) b