PostgreSQL:在一个语句中组合重复窗口函数(OVER / PARTITION BY)

时间:2018-04-15 15:06:29

标签: sql postgresql partitioning window-functions

我有一个更大的查询,我必须为多列选择第一个或最后一个值。

到目前为止,我的查询结构如下,符合预期 但是,由于我有大约10列,每个列我必须应用相同的窗口函数,即OVER (PARTITION BY ...)部分(如下面的示例列col4到col7),I我想知道是否有办法只写一次,而不是每次都要重复相同的行。

我在WINDOW w AS (...)子句之后尝试了FROM,然后通过OVER w AS ...为每个列引用了这个,但这不起作用。

这里的任何人都可以帮我吗?

我的查询结构(缩短):

SELECT DISTINCT
    c.col1
    , c.col2
    , c.col3
    , FIRST_VALUE(c.col4) OVER
        (
            PARTITION BY c.col1
            ORDER BY c.col1, c.col2, c.col3
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        ) AS col4
    , LAST_VALUE(c.col5) OVER
        (
            PARTITION BY c.col1
            ORDER BY c.col1, c.col2, c.col3
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        ) AS col5
    , LAST_VALUE(c.col6) OVER
        (
            PARTITION BY c.col1
            ORDER BY c.col1, c.col2, c.col3
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        ) AS col6
    , FIRST_VALUE(c.col7) OVER
        (
            PARTITION BY c.col1
            ORDER BY c.col1, c.col2, c.col3
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        ) AS col7
    /* ... */
FROM
    CUSTOMERS c
GROUP BY
    /* ... */
ORDER BY
    /* ... */

非常感谢您提供任何帮助

1 个答案:

答案 0 :(得分:2)

WINDOW应该 GROUP BY ... HAVING ...子句后<( ORDER BY ...之前),如The Fine Manual

这应该可行:

SELECT DISTINCT
    c.col1 , c.col2 , c.col3
    , FIRST_VALUE(c.col4) OVER www AS col4
    , LAST_VALUE(c.col5) OVER www AS col5
    , LAST_VALUE(c.col6) OVER www AS col6
    , FIRST_VALUE(c.col7) OVER www AS col7
    /* ... */
FROM
    CUSTOMERS c
GROUP BY 1,2,3
WINDOW www AS (PARTITION BY c.col1
            ORDER BY c.col1, c.col2, c.col3
            ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        )
ORDER BY 1,2,3
        ;