首页 > 解决方案 > 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

标签: postgresql

解决方案


您可以从将记录分组到组或范围开始。由于您的记录顺序很重要,这表明您可以使用窗口函数。您必须确定如何对这些组进行唯一命名。我建议你使用记录上面的重置次数。此语句的结果是:

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


推荐阅读