mysql - 找出单调递增的数字范围
问题描述
我在 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
谢谢。
解决方案
为了回答您的问题,您的数据需要有一个排序列。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。
推荐阅读
- ms-access - 是否可以通过远程桌面服务使用 MS-Access 应用程序?
- php - 如何显示列表,在 laravel 中选择选项
- python - 如何从包含字典列表的字典中获取项目
- javascript - Vue应用程序中的静音更新无限循环
- javascript - 如何使用http请求根据规则访问firebase实时数据库
- reactjs - React 路由器正在堆叠路由
- python - 根据索引填写数据
- javascript - 如何将单个对象迭代到定义格式内的多个对象的新数组中
- python - 我使用 Kivy UrlReguest 下载并显示 Json 文件,但在 android 上没有任何效果,为什么?
- c# - 检测 C# 表单外的鼠标点击