sql—在mysql中选择某个值下的连续行

r6l8ljro  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(382)

选择列低于某个值的连续行
我有一个包含以下数据的表格:

crashID     crash
-----------------------
1           189
2           144
3           8939        
4           748
5           988
6           102
7           392
8           482
9           185
10          101

我要选择连续行中最长的一行,这些行的崩溃值也低于某个treshold。我们假设这个例子是500。
如何在一个mysql查询中执行此操作(v8.0.1版)
期望输出如下:

crashID     crash
------------------
6           102
7           392
8           482
9           185
10          101
zysjyyx4

zysjyyx41#

有一种方法,对于mysql的旧版本。。。这个解决方案假设第一位没有关系。。。

SELECT m.* 
  FROM my_table m
  JOIN 
     ( SELECT MIN(crash_id) range_start
            , MAX(crash_id) range_end
         FROM 
            ( SELECT x.*
                   , CASE WHEN FLOOR(crash/500) * 500 = 0 AND @prev = FLOOR(crash/500) * 500 THEN @i:=@i ELSE @i:=@i+1 END i
                   , @prev:=FLOOR(crash/500)*500 prev 
                FROM my_table x
                   , (SELECT @prev:=null,@i:=0) vars 
               ORDER 
                  BY crash_id
            ) a
        GROUP
           BY i
        ORDER
           BY COUNT(*) DESC LIMIT 1
     ) n
    ON m.crash_id BETWEEN n.range_start AND n.range_end;
oalqel3c

oalqel3c2#

您可以尝试使用间隙和孤岛方法来解决它,假设每次崩溃lte 500都是一个孤岛,然后找到最大的孤岛:

SET @threshold = 500;
WITH cte1 AS (
    SELECT
        crashID,
        CASE WHEN crash <= @threshold THEN 1 ELSE 0 END AS island,
        ROW_NUMBER() OVER (ORDER BY crashID) rn1,
        ROW_NUMBER() OVER (PARTITION BY CASE WHEN crash <= @threshold THEN 1 ELSE 0 END ORDER BY crashID) rn2
    FROM t
), cte2 AS (
    SELECT MIN(crashID) AS fid, MAX(crashID) AS tid
    FROM cte1
    WHERE island = 1
    GROUP BY rn1 - rn2
    ORDER BY COUNT(*) DESC
    LIMIT 1
)
SELECT *
FROM t
WHERE crashID BETWEEN (SELECT fid FROM cte2) AND (SELECT tid FROM cte2);

小提琴

相关问题