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

时间:2019-06-10 05:11:19

标签: amazon-redshift window-functions column-alias

我正在查看我们的一些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,我会做类似的事情来删除一级嵌套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中是否可以提供类似的功能?

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

1 个答案:

答案 0 :(得分: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