mysql 如何根据行中的连续出现选择开始日期和结束日期

vatpfxk5  于 2023-10-15  发布在  Mysql
关注(0)|答案(2)|浏览(148)

我正在使用MySQL,遇到了一个问题。我想根据每个ID计数类型的连续出现,并仅选择出错误类型超过3次的ID。
另外,基于上面的结果,我想在结果中包括开始时间戳和结束时间戳。
我已经检查了其他职位,但没有线索如何解决它。
感谢任何建议。提前感谢您,并欢迎任何建议。
IDs with action type
我想展示的结果是截图。
ID A:具有4次连续错误,start_at是序列ID C:有3次连续错误,start_at是序列开始时的时间戳
result

gj3fmq9x

gj3fmq9x1#

尝试

SELECT d.id, MIN(dt) AS start_dt, MAX(dt) AS end_dt
FROM 
(
    SELECT 
        d.*, 
        row_number() OVER(PARTITION BY id ORDER BY dt) - row_number() OVER(PARTITION BY id, type ORDER BY dt) AS grp
    FROM DATA d
) d
WHERE d.type = 'Error'
GROUP BY d.id, d.grp HAVING( COUNT(d.id) >= 3 )
;
r3i60tvu

r3i60tvu2#

谢谢你,P3咨询。它的工作,我将深入到差距和岛屿的问题更多。下面是我编辑的结果与虚拟数据。

WITH DATA AS (
SELECT 'A' AS id, cast('2023-04-01 5:00:00' as datetime) AS dt, 'Success' AS type UNION ALL
SELECT 'A', cast('2023-04-01 5:30:00' as datetime), 'Error' UNION ALL
SELECT 'A', cast('2023-04-01 5:33:00' as datetime), 'Error' UNION ALL
SELECT 'A', cast('2023-04-01 5:34:00' as datetime), 'Error' UNION ALL
SELECT 'A', cast('2023-04-01 5:40:00' as datetime), 'Error' UNION ALL
SELECT 'B', cast('2023-04-01 4:00:00' as datetime), 'Success' UNION ALL
SELECT 'B', cast('2023-04-01 4:20:00' as datetime), 'Error' UNION ALL
SELECT 'B', cast('2023-04-01 4:45:00' as datetime), 'Error' UNION ALL
SELECT 'B', cast('2023-04-01 4:50:00' as datetime), 'Error' ),

base as (
  SELECT 
    d.*,
    row_number() OVER(PARTITION BY id ORDER BY dt) as rn1,
    row_number() OVER(PARTITION BY id, type ORDER BY dt) as rn2,
    row_number() OVER(PARTITION BY id ORDER BY dt) - row_number() OVER(PARTITION BY id, type ORDER BY dt) AS grp
FROM DATA d)

SELECT 
base.id,
base.type,
MIN(dt) AS start_dt, 
MAX(dt) AS end_dt,
COUNT(base.id) AS activities
FROM base
WHERE base.type = 'Error'
GROUP BY base.id, base.grp, base.type
HAVING(COUNT(base.id) >= 3 )
ORDER BY base.id;

相关问题