How to use a SQL window function to calculate a percentage of an aggregate

后端 未结 2 1425
情歌与酒
情歌与酒 2021-02-01 08:17

I need to calculate percentages of various dimensions in a table. I\'d like to simplify things by using window functions to calculate the denominator, however I am having an iss

2条回答
  •  不要未来只要你来
    2021-02-01 08:39

    I think you are looking for this:

    SELECT d1, d2, sum(v)/sum(sum(v)) OVER (PARTITION BY d1) AS share
    FROM   test
    GROUP  BY d1, d2;
    

    Produces the requested result.

    Window functions are applied after aggregate functions. The outer sum() in sum(sum(v)) OVER ... is a window function (attached OVER ... clause) while the inner sum() is an aggregate function.

    Effectively the same as:

    WITH x AS (
       SELECT d1, d2, sum(v) AS sv
       FROM   test
       GROUP  BY d1, d2
       )
    SELECT d1, d2, sv/sum(sv) OVER (PARTITION BY d1) AS share
    FROM   x;
    

    Or (without CTE):

    SELECT d1, d2, sv/sum(sv) OVER (PARTITION BY d1) AS share
    FROM  (
       SELECT d1, d2, sum(v) AS sv
       FROM   test
       GROUP  BY d1, d2
       ) x;
    

    Or @Mu's variant.

    Aside: Greenplum introduced correlated subqueries with version 4.2. See release notes.

提交回复
热议问题