【问题标题】:Rewrite correlated subquery, Redshift throwing This type of correlated subquery pattern is not supported yet Error重写相关子查询,Redshift 抛出这种类型的相关子查询模式尚不支持错误
【发布时间】:2020-05-29 05:32:12
【问题描述】:

我正在处理一个查询,该查询需要在 A.user_id=B.user_id 上将表 A 与表 B 连接起来,并且 B.day 小于 A.day 但最接近 A.day。

这是我写的:

Select A.user_id, A.date, b1.v1 from A
Left Join B as b1
on A.user_id=b1.user_id and b1.day=(Select max(day) from B as b2 where b2.user_id=A.user_id
and b2.day < A.day)

我在 python 中使用 psycopg2 执行此操作,它返回错误:This type of correlated subquery pattern is not supported yet

有人可以帮我重写一下,让它不使用相关子查询吗?

【问题讨论】:

    标签: sql left-join amazon-redshift correlated-subquery


    【解决方案1】:

    一种方法可以是:

    Select A.user_id, A.date, b1.v1, max(b1.day) 
    from A Left Join B as b1 on A.user_id=b1.user_id and b1.day < A.day 
    group by A.user_id, A.date, b1.v1;
    

    【讨论】:

      【解决方案2】:

      一种方法相当昂贵,但是 . . . :

      select . . .
      from (select A.user_id, A.date, b1.v1,
                   row_number() over (partition by a.user_id, a.date order by b.day desc) as seqnum
            from A Left Join
                 B 
                on A.user_id = b1.user_id and b.day < a.day
           ) ab
      where seqnum = 1;
      

      可能还有其他方法可以实现这一点 - 并且具有更好的性能。如果需要,请提出一个问题,提供示例数据、所需结果以及对您要实现的逻辑的清晰解释。

      【讨论】:

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