Redshift 是否支持 SELECT 中的用户定义变量?

Does Redshift support User-Defined Variables in SELECT?

我正在审查我们的一些 Redshift 查询并发现具有多层嵌套 select 的案例,如下所示:

    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,我会做这样的事情来删除一层嵌套 select:

    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 中做类似的事情?

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

您可以将 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