首页 > 解决方案 > 找出单调递增的数字范围

问题描述

我在 leetcode 上发现了这个问题:

给定一个表名 "numbers" 和 1 个列名 "id",如下所示: 2, 3, 5, 1, 4, 2, 7, 8 编写一个 SQL 脚本来找出单调递增的数字范围。答案:2-5、1-4、2-8

我的解决方案如下,由于我是 SQL 新手,所以有很多子查询,我只对select, from, where, group by. 你能告诉我我的查询是否正确吗?我相信存在比我的解决方案更简单的查询,但目前我不知道该怎么做。你能告诉我怎么做吗?

with x as
select current, increasing as a, lead(increasing,1,0) as b
from 
(
    (select current, (case when current > before then 1 else 0 end) as increasing
    from 
        (select id as current, lag(id,1,0) as before
         from table numbers)
     )
)

select t1.start, t2.end
(select current as start, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
from x
where a=0 and b=1) t1
inner join 
(select current as end, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
from x
where a=1 and b=0) t2
on t1.numrow = t2.numrow

谢谢。

标签: mysqlsql

解决方案


为了回答您的问题,您的数据需要有一个排序列。SQL 表表示无序(多)集,因此没有这样的列就没有排序。

用于lag()确定单调递增组的开始位置。然后进行累积求和以将分组分配给组。最后聚合:

select min(id), max(id)
from (select n.*,
             sum(case when prev_id < id then 0 else 1 end) over (order by <ordering col>) as grp
      from (select n.*,
                   lag(id) over (order by <ordering col>) as prev_n
            from numbers n
           ) n
     ) n
group by grp;

是一个 db<>fiddle。


推荐阅读