在sql中使用lag()初始化

c9x0cxw0  于 2021-06-26  发布在  Impala
关注(0)|答案(2)|浏览(446)

好吧,我到处都找过了,但找不到解决办法。
所以我有一张这样的table:

member_id public_id
a1        NULL
a1        123
a1        345
a2        612

我想添加一个新列,名为 conv . 使用以下规则填充数字:

IF PREVIOUSROW(member_id) <> member_id THEN 1
ELSE IF PREVIOUSROW(member_id) = member_id AND PREVIOUSROW(public_id) = NULL
    THEN PREVIOUSROW(THIS_COLUMN) + 1 <-- here is the inception
ELSE 1

我知道如何访问前一行,我可以使用 LAG() . 但是,如何从该列访问前一行,这也是使用 LAG() 在里面。
这是我的目标:

member_id public_id  conv
a1        NULL       1
a1        NULL       2
a1        NULL       3
a1        123        4
a1        345        1
a2        612        1

谢谢你的帮助!
所以,在我使用了你的解决方案之后,我得到了这样的结果:

member_id public_id  conv
a1        NULL       1
a1        NULL       2
a1        NULL       2
a1        123        2
a1        345        1
a2        612        1

因为解决办法是 conv+1 以及 conv 是1,所以最大值总是2

whitzsjs

whitzsjs1#

lag()接受一个偏移量,以便可以返回多条记录。我不知道您的数据库的确切语法,所以这里是sql server版本。
https://msdn.microsoft.com/en-us/library/hh231256.aspx

hs1ihplo

hs1ihplo2#

假设你用的是 Impala

select 
      member_id
    , public_id
    , case when (prev_member_id = member_id) and  prev_public_id is NULL
            then conv + 1 
            else conv 
      end as conv     
from (    
    select 
          member_id
        , public_id
        , lag(member_id) over( partition by member_id order by public_id asc nulls first) as prev_member_id
        , lag(public_id) over( partition by member_id order by public_id asc nulls first) as prev_public_id
        , 1 as conv 
    from z_test1 
)temp 
order by member_id, public_id asc nulls first;

相关问题