将sql server外部应用查询迁移到雪花查询

z8dt9xmd  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(210)

正在从sql server迁移到snowflake。卡在下面查询。在雪花中找不到任何等价物。对于外部查询中的每一行,我们进入内部查询以获得比外部查询中的datekey小的top datekey。

select a.datekey , a.userid, a.transactionid
    ,cast( cast(b.datekey as varchar(8)) as date) priorone
    from tableA a
    outer apply (select top 1 b.datekey
                  from tableA b where a.userid = b.userid
                  and b.transactionid < a.transactionid and b.datekey < a.datekey
    order by b.transactionid desc) as b

建议回答如下:

create or replace table tableA
   (datekey date , userid int ,transactionid int)
   insert into tableA
   values('2020-06-01',1,101),('2020-06-02',1,102),('2020-06-02',1,103),('2020-06-01',2,104),('2020-06-02',2,105)
    select 
    a.datekey, 
    a.userid, 
    a.transactionid
    ,(
        select b.datekey
        from tableA b 
        where 
            a.userid = b.userid
            and b.transactionid < a.transactionid 
            and b.datekey < a.datekey
        order by b.transactionid desc
        limit 1
    ) priorone
from tableA a
jhkqcmku

jhkqcmku1#

我想您要找的是snowflake中的lead()函数。它将为您保存子查询或连接:

select 
    datekey, 
    userid, 
    transactionid,
    lead(datekey) over (partition by userid order by datekey desc) as priorone
from tableA;

这将根据datekey的降序获得userid的下一条记录。
您还可以使用lag()并按相反的方式进行排序:

select 
    datekey, 
    userid, 
    transactionid,
    lag(datekey) over (partition by userid order by datekey asc) as priorone
from tableA;
mcdcgff0

mcdcgff02#

您只能从外部联接获得一列,因此可以将代码重新表述为直接相关的子查询。
雪花不支持 top ,但它具有与实现相同的功能 limit .
最后,你好像想把时间药水去掉 datekey :您可以使用 date() 为了这个。

select 
    a.datekey, 
    a.userid, 
    a.transactionid
    (
        select date(b.datekey)
        from tableA b 
        where 
            a.userid = b.userid
            and b.transactionid < a.transactionid 
            and b.datekey < a.datekey
        order by b.transactionid desc
        limit 1
    ) priorone
from tableA a

相关问题