I’m using Postgress DB in AWS and creating some views with calculations.
I have multiple rows with the same ID but different Units and Subunits.
I would like to get a Sum based on Value_1 and Value_2 in the SUM column.
Value_1 and Value_2 are always identical within the same ID but sometimes they are NULL.
I need a formula to calculate the SUM based on the ID.
The SUM will be identicall for all the rows with the same ID.
Input:
ID | unit | sub_unit | value_1 | value_2 | sum |
---|---|---|---|---|---|
1 | A | 1 | NULL | 10 | NULL |
1 | A | 2 | NULL | 10 | NULL |
1 | A | 3 | NULL | 10 | NULL |
1 | A | 4 | NULL | 10 | NULL |
1 | B | 1 | 5 | NULL | NULL |
1 | B | 2 | 5 | NULL | NULL |
1 | B | 3 | NULL | NULL | NULL |
1 | B | 4 | NULL | NULL | NULL |
I have tryed with this querry but since the values are in different rows it results always in NULL
Selcet ID, unit, sub_unit, value_1, value_2, value_1 * value_2 AS sum FROM t1
I’m not sure what would be best practice to solve this problem.
Should I try to fill all the NULL fields with one of the values? This should result in giving me the SUM for each row (SUM will be the same for each row with the same ID)
¨
How can I get the first not NULL value from a column based on an ID and fill the other fields with the same ID with this value?
Maybe something like this?:
ID | unit | sub_unit | value_1 | value_2 | sum |
---|---|---|---|---|---|
1 | A | 1 | 5 | 10 | 50 |
1 | A | 2 | 5 | 10 | 50 |
1 | A | 3 | 5 | 10 | 50 |
1 | A | 4 | 5 | 10 | 50 |
1 | B | 1 | 5 | 10 | 50 |
1 | B | 2 | 5 | 10 | 50 |
1 | B | 3 | 5 | 10 | 50 |
1 | B | 4 | 5 | 10 | 50 |
2
Answers
I would suggest that you use window functions, straightforward and easy to read.
DB-fiddle
I don’t quite follow why your sum and other columns should be the way they are (such as val1 is same for all), but this solution returns your desired output:
View on DB Fiddle