【问题标题】:Find avg, min, and max of grouped by rows查找按行分组的平均值、最小值和最大值
【发布时间】:2021-01-15 14:33:16
【问题描述】:

我创建了以下架构:

CREATE TABLE test (
  id INT,
  stat_id INT,
  time DATETIME
);

INSERT INTO test (id, stat_id, time) VALUES (1, 1, '2020-09-21 00:02:31');
INSERT INTO test (id, stat_id, time) VALUES (5, 1, '2020-09-21 00:06:31');
INSERT INTO test (id, stat_id, time) VALUES (2, 2, '2020-09-19 00:08:31');
INSERT INTO test (id, stat_id, time) VALUES (3, 2, '2020-09-21 00:03:31');
INSERT INTO test (id, stat_id, time) VALUES (6, 2, '2020-09-23 00:02:31');
INSERT INTO test (id, stat_id, time) VALUES (4, 2, '2020-09-27 00:04:31');
INSERT INTO test (id, stat_id, time) VALUES (7, 3, '2020-09-20 00:04:31');
INSERT INTO test (id, stat_id, time) VALUES (8, 3, '2020-09-23 00:05:31');

https://www.db-fiddle.com/f/6CRv6XqYMAfkBHEBhz1zGe/1

我有 3 个不同的 stat_id 组。

它们按 id 排序(从小到大)。

我需要找出每组中的一个事件与下一个事件之间的平均持续时间。

例如,对于 site_id = 2,我需要得到 2020-09-21 和 2020-09-19 之间的差异,然后是 2020-09-23 和 2020-09-21,然后是 2020-09- 27 和 2020-09-23。

然后我需要获取每行之间的平均持续时间、最长时间(即 2020 年 9 月 27 日和 2020 年 9 月 23 日之间的时间)和最短时间。

我需要为所有 3 个 stat_id 组执行此操作。

我基本上是在查看每个 stat_id 组创建新行平均需要多长时间。

我尝试了类似的方法:

select 
    stat_id,
    AVG(time) as avg,
    timestampdiff(hour, min(time), max(time))   as diff_in_hours,
from test
group by stat_id;

但显然这是错误的。它给出了错误的平均值,只是给出了每组中最大和最小之间的差异,这并不是我想要的。我不知道如何区分一行和上一行?

【问题讨论】:

  • 期望的结果应该是什么样子。请相应地编辑您的问题。

标签: mysql sql datetime average window-functions


【解决方案1】:

一个选项使用lag()

select stat_id, avg(diff) avg_diff
from (
    select t.*, 
        timestampdiff(hour, lag(time) over(partition by stat_id order by id), time) diff
    from test t
) t
group by stat_id

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 2018-09-04
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多