我如何计算行之间的间隙

How I calculate gaps between rows

现在我在我的应用程序中加入了一些并行性 ProcessXX,我不确定数据是否可以按正确的顺序处理。所以我正在查询 return 下限和上限以传递给 ProcessZZ.

我的 table avl_pool 有 avl_idhas_link 以及其他一些字段和稳定的数据流,当新数据到达时它们以 [=17= 开头],当 ProcessX 完成行时 has_link 有 link 值 xxxx 是一些数字。

现在在下一步中我必须只处理那些带有 link 的行,但我不能跳过行,因为顺序非常重要。

在这种情况下我需要ProcessZZ(23561211, 23561219)

rn | avl_id    | has_link
1  | 23561211  | xxxx     --  start
2  | 23561212  | xxxx
3  | 23561213  | xxxx
4  | 23561214  | xxxx
5  | 23561215  | xxxx
6  | 23561216  | xxxx
7  | 23561217  | xxxx
8  | 23561218  | xxxx
9  | 23561219  | xxxx     -- end
10 | 23561220  | null
11 | 23561221  | xxxx
12 | 23561222  | xxxx
13 | 23561223  | xxxx

目前我有:

-- starting avl_id need to be send to ProcessZZ
SELECT MIN(avl_id) as min_avl_id
FROM avl_db.avl_pool
WHERE NOT has_link IS NULL

-- first avl_id still on hands of ProcessXX ( but can be null )
SELECT MIN(avl_id) as max_avl_id -- here need add a LAG
FROM avl_db.avl_pool
WHERE has_link IS NULL
  AND avl_id > (SELECT MIN(avl_id) 
                FROM avl_db.avl_pool
                WHERE NOT has_link IS NULL)

-- In case everyone has_link already the upper limit is the last one on the table.
SELECT MAX(avl_id) as max_avl_id
FROM avl_db.avl_pool

我可以把所有东西都放在多个 CTE 中,return 这两个结果,但我认为这可以像一些岛一样处理,但不确定如何处理。

所以查询应该看起来像

SELECT min_avl_id, min_avl_id
FROM cte 


min_avl_id  | min_avl_id
23561211    |  23561219

如果我没理解错的话,你想给每个块分配一个序号。此数字由 has_link 中的 NULL 值划分。

如果这是问题所在,则累加和解决问题:

select p.*,
       sum(case when has_link is null then 1 else 0 end) over (order by rn) as grp
from avl_db.avl_pool p;

这实际上包括输出中的 NULL 个值。最简单的方法可能是子查询:

select p.*
from (select p.*,
             sum(case when has_link is null then 1 else 0 end) over (order by rn) as grp
      from avl_db.avl_pool p
     ) p
where has_link is not null;