【问题标题】:Snowflake - update with correlated subquery using timediffSnowflake - 使用 timediff 更新相关子查询
【发布时间】:2019-02-25 14:41:43
【问题描述】:

我在雪花数据库上运行这个查询:

UPDATE "click" c
SET "Registration_score" =
(SELECT COUNT(*) FROM "trackingpoint" t
WHERE 1=1
AND c."CookieID" = t."CookieID"
AND t."page" ilike '%Registration complete'
AND TIMEDIFF(minute,c."Timestamp",t."Timestamp") < 4320
AND TIMEDIFF(second,c."Timestamp",t."Timestamp") > 0);

数据库返回Unsupported subquery type cannot be evaluated。但是,如果我在没有最后两个条件的情况下运行它(使用 TIMEDIFF),它就可以正常工作。我确认这些查询的实际 TIMEDIFF 语句没有问题:

select count(*) from "trackingpoint"
where TIMEDIFF(minute, '2018-01-01', "Timestamp") > 604233;
select count(*) from "click"
where TIMEDIFF(minute, '2018-01-01', "Timestamp") > 604233;

这些工作没有问题。我看不出 TIMEDIFF 条件应该阻止数据库返回结果的原因。知道我应该改变什么才能让它工作吗?

【问题讨论】:

标签: sql sql-update correlated-subquery snowflake-cloud-data-platform


【解决方案1】:

所以使用以下设置

create table click (id number, 
   timestamp timestamp_ntz,
   cookieid number,
   Registration_score number);
create table trackingpoint(id number, 
   timestamp timestamp_ntz, 
   cookieid number, 
   page text );


insert into click values (1,'2018-03-20', 101, 0),
    (2,'2019-03-20', 102, 0);
insert into trackingpoint values (1,'2018-03-20 00:00:10', 101, 'user reg comp'),
    (2,'2018-03-20 00:00:11', 102, 'user reg comp'),
    (3,'2018-03-20 00:00:13', 102, 'pet reg comp'),
    (4,'2018-03-20 00:00:15', 102, 'happy dance');

你可以看到我们得到了我们期望的行

select c.*, t.*
from click c
join trackingpoint t 
    on c.cookieid = t.cookieid ;

现在有两种方法可以得到你的计数,第一种是你有的,如果你只计算一个东西,这很好,因为所有的规则都是加入过滤:

select c.id,
  count(1) as new_score
from click c
join trackingpoint t 
    on c.cookieid = t.cookieid
    and t.page ilike '%reg comp'
    and TIMEDIFF(minute, c.timestamp, t.timestamp) < 4320
group by 1;

或者你可以(在雪花语法中)将计数移动到聚合/选择端,如果这是你需要的,那么得到多个答案(这是我发现自己更多的地方,因此我提出它):

select c.id,
    sum(iff(t.page ilike '%reg comp' AND TIMEDIFF(minute, c.timestamp, t.timestamp) < 4320, 1, 0)) as new_score
from click c
join trackingpoint t 
    on c.cookieid = t.cookieid
group by 1;

因此将其插入到 UPDATE 模式中(参见文档中的最后一个示例) https://docs.snowflake.net/manuals/sql-reference/sql/update.html

您可以移动到单个子选择,而不是雪花不支持的关联子查询,这是您收到的错误消息。

UPDATE click c
SET Registration_score = s.new_score
from (
    select ic.id,
        count(*) as new_score
    from click ic
    join trackingpoint it 
        on ic.cookieid = it.cookieid
        and it.page ilike '%reg comp'
        and TIMEDIFF(minute, ic.timestamp, it.timestamp) < 4320
    group by 1) as s
WHERE c.id = s.id; 

添加 TIMEDIFF 将您的查询变成相关子查询的原因,是 UPDATE 的每一行,现在与子查询结果相关,相关性。解决方法是制作“大而简单”的子查询并加入其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多