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

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

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

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

建议回答如下:

  1. create or replace table tableA
  2. (datekey date , userid int ,transactionid int)
  3. insert into tableA
  4. 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)
  5. select
  6. a.datekey,
  7. a.userid,
  8. a.transactionid
  9. ,(
  10. select b.datekey
  11. from tableA b
  12. where
  13. a.userid = b.userid
  14. and b.transactionid < a.transactionid
  15. and b.datekey < a.datekey
  16. order by b.transactionid desc
  17. limit 1
  18. ) priorone
  19. from tableA a
jhkqcmku

jhkqcmku1#

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

  1. select
  2. datekey,
  3. userid,
  4. transactionid,
  5. lead(datekey) over (partition by userid order by datekey desc) as priorone
  6. from tableA;

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

  1. select
  2. datekey,
  3. userid,
  4. transactionid,
  5. lag(datekey) over (partition by userid order by datekey asc) as priorone
  6. from tableA;
展开查看全部
mcdcgff0

mcdcgff02#

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

  1. select
  2. a.datekey,
  3. a.userid,
  4. a.transactionid
  5. (
  6. select date(b.datekey)
  7. from tableA b
  8. where
  9. a.userid = b.userid
  10. and b.transactionid < a.transactionid
  11. and b.datekey < a.datekey
  12. order by b.transactionid desc
  13. limit 1
  14. ) priorone
  15. from tableA a
展开查看全部

相关问题