我如何将此查询编写为连接而不是相关查询?

How would I write this query as a join instead of a correlated query?

因此,Netezza 不能在 SELECT 语句中使用相关子查询,不幸的是,在我的特定情况下,我想不出避免这种情况的单一方法。我正在考虑用 ROW_NUMBER() 做点什么;但是,我不能在 HAVING 子句中包含窗口函数。

我有以下查询:

select 
    a.*
    ,(  select b.col1
        from b
        where b.ky = a.ky
            and a.date <= b.date
        order by b.date desc
        limit 1
    ) as new_col
from a

有什么建议吗?

我不太确定我理解你的问题,但这就是你要找的吗?

SELECT TOP 1 a.*, b.col1 FROM a JOIN b ON a.ky = b.ky
WHERE a.date <= b.date ORDER BY b.date desc

这应该return预期结果:

select *
from 
 (
   select 
      a.*
     ,b.col1 as b_col1
     ,row_number() 
      over (partition by a.ky
            order by b.date desc NULLS FIRST) as rn 
   from a left join b
   where b.ky = a.ky 
   and a.date <= b.date
 ) as dt
where rn = 1