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
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.