如何列出没有给定子句间隙的最新系列?

How to list the latest series with no gaps of a given clause?

给定以下示例table:

+-----------+
| Id | Name |  
+----+------+
| 1  | A    |
| 2  | B    |
| 3  | B    |
| 4  | C    |
| 5  | A    |
| 6  | B    |
| 7  | B    |
| 8  | B    |
| 9  | B    |
| 10 | X    |
+----+------+
 

我想查询得到以下结果:

+----+------+
| 6  | B    |
| 7  | B    |
| 8  | B    |
| 9  | B    |
+----+------+

我能做的最好的查询是:

SELECT * FROM 
 (SELECT id, name, LEAD(id) OVER (ORDER BY id) t 
  FROM test WHERE name = 'B' ORDER BY id) 
WHERE ID <> t-1;

sqlfiddle here

如果您想要长度和开始位置:

select min(id), max(id)
from (select t.*,
             row_number() over (order by id) as seqnum,
             row_number() over (partition by name order by id) as seqnum_1
      from test t
     ) t
where name = 'B'
group by (seqnum - seqnum_1)
order by min(id) desc
fetch first 1 row only;

您可以重新加入 table 以获取原始行。

另一种方法使用 window 函数来计算给定行之后 非 B 的数量。 . .然后选择第一个:

select t.*
from (select t.*,
             dense_rank() over (order by nonbs_after asc) as grp
      from (select t.*, 
                   sum(case when name <> 'B' then 1 else 0 end) over (order by id desc) as nonbs_after
            from test t
           ) t
      where name = 'B'
     ) t
where grp = 1;

Here 是一个 db<>fiddle.