postgresql - Postgresql 查询每个范围内的第一个和最后一个
问题描述
我有桌子
ID | 机器ID | 重置 |
---|---|---|
1 | 1 | 错误的 |
2 | 1 | 错误的 |
3 | 1 | 错误的 |
4 | 1 | 真的 |
5 | 1 | 错误的 |
15 | 1 | 真的 |
17 | 1 | 错误的 |
20 | 2 | 错误的 |
21 | 2 | 错误的 |
25 | 2 | 错误的 |
30 | 2 | 错误的 |
我不知道如何找到每台机器的第一个和最后一个 id。重置为下一行创建新范围。结果应如下所示:
机器ID | 起始编号 | 结束ID |
---|---|---|
1 | 1 | 3 |
1 | 4 | 5 |
1 | 15 | 17 |
2 | 20 | 30 |
解决方案
您可以从将记录分组到组或范围开始。由于您的记录顺序很重要,这表明您可以使用窗口函数。您必须确定如何对这些组进行唯一命名。我建议你使用记录上面的重置次数。此语句的结果是:
SELECT *
, SUM(case when reset then 1 else 0 end) over (partition by machineid order by id) as reset_group
FROM
test;
之后找到开始和结束 id 是一个简单的GROUP BY语句:
SELECT
machineid, MIN(id) as startid, MAX(id) as endid
FROM (
SELECT machineid, id
, SUM(case when reset then 1 else 0 end) over (partition by machineid order by id) as reset_group
FROM
test
) as grouped
GROUP BY
machineid, reset_group
ORDER BY
machineid, startid;
请尝试一下:db<>fiddle
推荐阅读
- android-architecture-components - Android导航库不打开深层链接
- spring - Spring 5 WebFlux Mono 和 Flux
- php - 在 Couch DB 的情况下,如何使用带有 Mongo 表达式的最佳范围查询来获取文档?
- java - 从 HTML 创建 PDF 文件会导致文本超出右边距(java + itext)
- iis - .WOFF2 字体未输出到生产
- sql - 如何使用遍历 CTE 生成树路径
- javascript - 如何在 Node.js 中使用带有空格的 JSON 键获取 JSON 对象值
- javascript - 运行 javascript 按钮 c#
- javascript - 从我的函数返回结果
- dart - 如何在 Flutter 中为 Container 小部件自定义/旋转 BoxDecoration?