I have a Postgres table like:
id | value | category
0 | 10 | a
1 | 11 | b
2 | 50 | b
3 | 20 | a
and I want the following (where the expression in the last column is evaluated, of course):
id | value | category | weight
0 | 10 | a | 10 / (10+20)
1 | 11 | b | 11 / (11+50)
2 | 50 | b | 50 / (11+50)
3 | 20 | a | 20 / (10+20)
Using 2 queries you could first aggregate the per-category totals into a temporary table using select category, sum(value) from table0 group by category
, and then divide the original table by the temporary table (by matching the category).
But how can I do this in Postgres in a single query?
2
Answers
You can use window function for that: fiddle
I hope this might help you
First Create Table named "t"
Insert Data into table
Data in table
Now Query
Result