mysql - SQL:找出响应时间的最大百分比变化

标签 mysql sql statistics

我正在尝试按照从一个时间段到下一个时间段的响应时间总体减少量最大的顺序计算并列出网站。

我并不严格需要使用单个查询来执行此操作,我可以运行多个查询。

网站:

| id | url                    |
| 1  | stackoverflow.com      |
| 2  | serverfault.com        |
| 3  | stackexchange.com      |

回复:

| id | website_id | response_time | created_at |
| 1  | 1          | 93.26         | 2014-01-28 11:51:39
| 2  | 1          | 99.46         | 2014-01-28 11:52:38
| 2  | 1          | 94.51         | 2014-01-28 11:53:38
| 2  | 1          | 104.46        | 2014-01-28 11:54:38
| 2  | 1          | 85.46         | 2014-01-28 11:56:38
| 2  | 1          | 100.00        | 2014-01-28 11:57:36
| 2  | 1          | 50.00         | 2014-01-28 11:58:37
| 2  | 2          | 100.00        | 2014-01-28 11:58:38
| 2  | 2          | 80            | 2014-01-28 11:58:39

理想情况下,结果应该是这样的:

| percentage_change | website_id | 
| 52                | 1 | 
| 20                | 2 | 

我已经弄清楚了最大响应时间,但不知道如何执行另一个查询来计算最低响应时间,然后进行数学运算,然后对数学运算进行排序。

SELECT * FROM websites
LEFT JOIN (
SELECT distinct * 
       FROM responses
       ORDER BY response_time desc) responsetable
ON websites.id=responsetable.website_id group by website_id

谢谢

最佳答案

您需要等效于 lag()lead() 函数。在 MySQL 中,我使用相关子查询执行此操作:

select website_id, max(1 - (prev_response_time / response_time)) * 100
from (select t.*,
             (select t2.response_time
              from table t2
              where t2.website_id = t.website_id and
                    t2.created_at < t.created_at
              order by t2.created_at desc
              limit 1
             ) as prev_response_time
      from table t
     ) t
group by website_id;

编辑:

如果你想要从最高到最低的变化:

select website_id, (1 - min(response_time) / max(response_time)) * 100
from table t
group by website_id;

关于mysql - SQL:找出响应时间的最大百分比变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21412640/

相关文章:

Mysql root 密码重置后不起作用

php - 我可以在同一页面上使用多个内容类型吗?

mysql - 更新到 mysql 8 安装后 mysql gem 出现问题

sql - 如何找到上个月的最后一天 'working'?

sql - 为表格中的每一行选择上一个日期

java - PHP MySQL 和 Android 连接

mysql - 从两个 INNER JOINS 更新

sql - 在 SQL Server 中通过标准差消除异常值

go - 如何计算 Go 中超几何分布的 p 值?

MySQL生成年龄金字塔