Postgresql查询在每个范围中都是第一个和最后一个

Postgresql查询在每个范围中都是第一个和最后一个,postgresql,Postgresql,我有一张桌子 身份证件 机械人 重置 1. 1. 假的 2. 1. 假的 3. 1. 假的 4. 1. 真的 5. 1. 假的 15 1. 真的 17 1. 假的 20 2. 假的 21 2. 假的 25 2. 假的 30 2. 假的 您可以从将记录分组到组或范围开始。由于您记录的顺序很重要,它表明您可以利用。您必须确定如何对这些组进行唯一命名。我建议您使用记录上方的重置次数。这一结果与该声明相一致: SELECT * , SUM(case when reset then 1 else 0 e

我有一张桌子

身份证件 机械人 重置 1. 1. 假的 2. 1. 假的 3. 1. 假的 4. 1. 真的 5. 1. 假的 15 1. 真的 17 1. 假的 20 2. 假的 21 2. 假的 25 2. 假的 30 2. 假的
您可以从将记录分组到组或范围开始。由于您记录的顺序很重要,它表明您可以利用。您必须确定如何对这些组进行唯一命名。我建议您使用记录上方的重置次数。这一结果与该声明相一致:

SELECT *
 , SUM(case when reset then 1 else 0 end) over (partition by machineid order by id) as reset_group
FROM 
  test;
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;
之后,查找开始和结束ID是一个简单的GROUP BY语句:

SELECT *
 , SUM(case when reset then 1 else 0 end) over (partition by machineid order by id) as reset_group
FROM 
  test;
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;
请试一试:

这个问题是给你的。