每个新ID如何从0开始计数?

问题描述 投票:0回答:1

我构建了以下查询,它给出了以下输出...

with tb1 as
(
    select  id
        ,row_number() over(order by id)-1 as lag_0
    from id_store
),
tb2 as
(
    select *
        ,lag(lag_0) over(order by id) as lag_1
    from tb1 
),
tb3 as
(
    select *
        ,lag(lag_1) over(order by id) as lag_2
    from tb2
),
tb4 as
(
    select *
        ,lag(lag_2) over(order by id) as lag_3
    from tb3
)
    select *
         ,lag(lag_3) over(order by id) as lag_4
    from tb4
id lag_0 lag_1 lag_2 lag_3 lag_4
213 0
215 1 0
217 2 1 0
313 3 2 1 0
315 4 3 2 1 0

所需的输出就是我想要的。为了简单起见,我只添加了五个 id。我也尝试了交叉连接,但得到了一些奇怪的结果。

id 群组名称 ord_num
213 lag_0 0
215 lag_0 1
217 lag_0 2
313 lag_0 3
315 lag_0 4
213 lag_1
215 lag_1 0
217 lag_1 1
313 lag_1 2
315 lag_1 3
213 lag_2
215 lag_2
217 lag_2 0
313 lag_2 1
315 lag_2 2
213 lag_3
215 lag_3
217 lag_3
313 lag_3 0
315 lag_3 1
213 lag_4
215 lag_4
217 lag_4
313 lag_4
315 lag_4 0
sql amazon-redshift
1个回答
0
投票
--      S a m p l e    D a t a : 
Create Table id_store (id Int);
Insert Into id_store 
VALUES (213), (215), (217), (313), (315);

一种选择是使用递归 CTE 生成行并准备数据以获取预期结果。

WITH 
  Recursive tb1 (pass, id, group_name, ord, rn) AS
    ( Select 1, id, 'lag_0' as group_name, 0 as ord, 
             Row_NUmber() Over(Order By id) as rn
      From id_store 
     UNION ALL 
      Select pass + 1, id, Concat('lag_', pass), 
             Case When rn > ord + 1 then ord + 1 End, rn
      From   tb1
      Where  pass < 5
    )
Select id, group_name, rn - 1 - ord as ord_num
From   tb1;

结果:

id 群组名称 ord_num
213 lag_0 0
215 lag_0 1
217 lag_0 2
313 lag_0 3
315 lag_0 4
213 lag_1
215 lag_1 0
217 lag_1 1
313 lag_1 2
315 lag_1 3
213 lag_2
215 lag_2
217 lag_2 0
313 lag_2 1
315 lag_2 2
213 lag_3
215 lag_3
217 lag_3
313 lag_3 0
315 lag_3 1
213 lag_4
215 lag_4
217 lag_4
313 lag_4
315 lag_4 0

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.