0

我正在查看我们的一些 Redshift 查询,发现具有多个嵌套选择级别的案例,如下所示:

    LEFT JOIN
    (
        SELECT *
        FROM (
            SELECT
                id,
                created_at,
                min(created_at) OVER (PARTITION BY id, slug) AS transition_date
            FROM table
            WHERE status = 'cancelled'
            GROUP BY id, Y, Z, created_at
        )
        WHERE created_at = transition_date
    ) t1 ON b.id = t1.id

如果这是 MySQL,我会做这样的事情来删除一级嵌套选择:

    LEFT JOIN
    (
        SELECT
            id,
            created_at,
            @tdate := min(created_at) OVER (PARTITION BY id, slug) AS transition_date
        FROM table
        WHERE status = 'cancelled' and @tdate = bul.created_at
        GROUP BY id, Y, Z, created_at
    ) t1 ON b.id = t1.id

在 RedShift 中有可能有类似的东西吗?

---更新忘记在嵌套的SELECT中包含GROUP BY,这可能会影响答案

4

1 回答 1

0

您可以将 transition_date 的条件移动到 JOIN 条件中:

LEFT JOIN
(
    SELECT
        id,
        created_at,
        min(created_at) OVER (PARTITION BY id, slug) AS transition_date
    FROM table
    WHERE status = 'cancelled'
) t1 ON b.id = t1.id AND t1.created_at = t1.transition_date
于 2019-06-10T05:16:10.850 回答