I need to calculate delta between two tables. See the example:
First, I have tables A and B
table A
ID | Value |
---|---|
Id 1 | 10 |
Id 2 | 20 |
Id 3 | 30 |
Id 4 | 40 |
table B
ID | Value |
---|---|
Id 1 | 10 |
Id 2 | 15 |
So now in table B:
- there is no Id 3 and Id 4 in B.
- value of Id 2 differs.
- id 1 is the same in both tables
What I need to do is to calculate table C wich contains diffence between A and B
table C
ID | Value |
---|---|
Id 2 | -5 |
Id 3 | 30 |
Id 4 | 40 |
There is no Id A in table C because it has same values in both A and B.
Any help will be appreciated.
Thanks in advance.
PostgreSQL DB.
Any help will be appreciated.
Thanks in advance.
2
Answers
Assuming that both table always have the same columns, you can try the following approach –
Heres the query, I have tested it here.
COALESCE: Handle cases when there is no match in second table.
Output:
I am expecting you have already created table C.
I hope it helps.