i have a table like this:
ID | num_A | num_B |
---|---|---|
1 | 1 | 168 |
2 | 1 | 4 |
2 | 5 | 24 |
2 | 6 | 24 |
3 | 1 | 36 |
So, num_A and num_B represent a fraction. That means for ID=1, i have 1/168, ID=2 —> (1/4)+(5/24)+(6/24) = 17/24, ID=3 –> 1/36….
I need to add 2 columns, one with the sum(num_A) and one with the denominator num_B, for those with the same ID. So the example should be:
ID | num_A | num_B | sumA | denom_B |
---|---|---|---|---|
1 | 1 | 168 | 1 | 168 |
2 | 1 | 4 | 17 | 24 |
2 | 5 | 24 | 17 | 24 |
2 | 6 | 24 | 17 | 24 |
3 | 1 | 36 | 1 | 36 |
My problem is that i dont know how to calculate the denominator for each different fraction in postgres.
2
Answers
In general PostgreSQL provides the
LCM
function that returns the least common multiple (the smallest strictly positive number that is an integral multiple of both inputs), but it takes only two arguments and cannot be used to process rowset column values.Thus, to get the LCM of rows with the same
ID
value, you can use a recursive CTE to process the rows one by one, using theLCM
function with the LCM calculated in the previous step (in the first step equal to the value ofnum_B
) and the current value ofnum_B
as arguments. This will produce the LCM value of all previousnum_B
and the current value for each row.Finally, you can get the maximum (the last if to be exact, it would be the maximum anyway) calculated LCM value for rows grouped by
ID
and that will be the LCM for allnum_B
values with the sameID
.The rest is simple – divide, multiply and sum.
Query:
Output
DEMO
I think you are trying to simulate fraction addition,
Try the following query:
See demo from db<>fiddle.
To understand how the query works consider the following image:
where the
ROUND(EXP(SUM(LN(num_b)) over (partition by id)))
will find the multiplication of the dividends for each id. (According to this post)