mysql - 查找按时间间隔分组的响应时间
问题描述
我有一张桌子,上面有某些日志及其响应时间。我可以通过执行以下操作查询表以获取最近 1000 条记录的平均响应时间:
SELECT timestamp, count(*), avg(response_time) FROM table ORDER BY timestamp DESC LIMIT 1000
-- timestamp count(*) avg(response_time)
-- 2020-03-17 11:58:37 1000 0.27
但是,我想在过去每千条记录中得到 N 条记录(以查看响应时间随时间的进展,以 1000 个请求为单位),即:
SELECT timestamp, count(*), avg(response_time) FROM table ORDER BY timestamp DESC LIMIT 1000
UNION
SELECT timestamp, count(*), avg(response_time) FROM table ORDER BY timestamp DESC LIMIT 1000, 1000
UNION ...
-- timestamp count(*) avg(response_time)
-- 2020-03-17 11:58:37 1000 0.27
-- 2020-03-17 11:38:09 1000 0.52
-- 2020-03-17 11:04:11 1000 1.04
-- and keep going, in groups of 1000 records...
是否有一种更清洁的方法可以做到这一点,我可以按 1000 个块对事物进行分组?
解决方案
你似乎想要:
SELECT count(*) no_records, avg(response_time) avg_response_time
FROM table
WHERE timestamp >= now() - interval 1 day
如果您希望按小时计算:
SELECT
date_format(timestamp, '%Y-%m-%d %h:00:00') hr,
count(*) no_records,
avg(response_time) avg_response_time
FROM table
WHERE timestamp >= now() - interval 1 day
GROUP BY date_format(timestamp, '%Y-%m-%d %h:00:00)
ORDER BY hr
或者,如果您想按 1000 条记录的块分组,那么(假设 MySQL 8.0),您可以使用row_number()
:
SELECT
min(timestamp) first_timestamp,
last(timestamp) first_timestamp,
count(*) no_records,
avg(response_time) avg_response_time
FROM table
WHERE timestamp >= now() - interval 1 day
GROUP BY floor((row_number() over(order by timestamp) - 1) / 1000)
ORDER BY first_timestamp
推荐阅读
- docker - 在 gitlab.com(公共版本)中运行 docker-compose 时使用哪个主机名
- python - 使用 pip 安装后的 matplotlib 错误
- oracle - 在 oracle PLSQL 中以以下给定方式对特定列应用分组并设置记录的顺序
- html - 如何使用 CSS/SVG 创建这个形状?
- algorithm - 如何找到元素之间的最小距离大于某个值且元素值之和最大的子集?
- sqldatareader - 如何使用 SQL Data Reader 查看数据库中的数量?
- ios - iOS 中最简单的 webview 应用程序 - 无法运行
- visual-studio-code - 从 VScode 打开 JupyterNotebook 到浏览器
- python - 使用 OpenCV 检测人脸时相机滞后
- c++ - CMake 不会链接我的库,make 文件会