SQL Presto:不支持相关子查询

SQL Presto: correlated subquery is not supported

考虑 table x

id,val
1,100
3,300

和tabley

id
1
2
3

对于 y 的每一行,我想要来自 xval,其中来自 y 的 id 等于或最接近 id来自 x 这样的:

id,val
1,100
2,100
3,300

我试图找到与相关子查询最接近的 ID:

WITH 
x AS (SELECT * FROM (VALUES (1, 100),(3, 300)) AS t(id, val)),
y AS (SELECT * FROM (VALUES 1,2,3) AS t(id))
SELECT *, (
    SELECT x.id
    FROM x
    WHERE x.id <= y.id
    ORDER BY x.id DESC
    LIMIT 1
) as closest_id
FROM y

但是我明白了

SYNTAX_ERROR: line 5:5: Given correlated subquery is not supported

我也试过左连接:

SELECT *
FROM y
LEFT JOIN x ON x.id <= (
    SELECT MAX(xbis.id) FROM x AS xbis WHERE xbis.id <= y.id
)

但是我得到了错误

SYNTAX_ERROR: line 7:5: Correlated subquery in given context is not supported

你这样使用我认为它的工作...

SELECT *, (
    SELECT top 1  x.val
    FROM x
    WHERE x.id <= y.id
    ORDER BY x.id DESC
    
) as closest_id
FROM y

您可以尝试根据less then条件加入,然后对结果进行分组,从分组中找到需要的数据:

WITH 
x AS (SELECT * FROM (VALUES (1, 100),(3, 300),(4, 400)) AS t(id, val)),
y AS (SELECT * FROM (VALUES 1,2,3,4) AS t(id))

SELECT y.id as yId,
    max(x.id) as xId,
    max_by(x.val, x.id) as val
FROM y
JOIN x on x.id <= y.id
GROUP BY y.id
ORDER BY y.id

输出:

yId xId val
1 1 100
2 1 100
3 3 300
4 4 400