I have a postgresql table containing movements of different elements (models) between warehouses.
For example, the following entry means that 5 units of Model 1 were sent from repository 1 to 2:
source target model units
------ ------ ----- -----
1 2 1 5
I am trying to build an SQL query to get the difference between the units sent and received, grouped by model. Again with an example:
source target model units
------ ------ ----- -----
1 2 1 5 -- 5 sent from 1 to 2
1 2 2 1
2 1 1 2 -- 2 sent from 2 to 1
2 1 1 1 -- 1 more sent from 2 to 1
The result should be:
source target model diff
------ ------ ----- ----
1 2 1 2 -- 5 sent minus 3 received
1 2 2 1
I wonder if this is possible with a single SQL query .
Here is the creation of the script table and some data, just in case someone wants to try it:
CREATE TEMP TABLE movements
(
source INTEGER,
target INTEGER,
model INTEGER,
units INTEGER
);
insert into movements values (1,2,1,5);
insert into movements values (1,2,2,1);
insert into movements values (2,1,1,2);
insert into movements values (2,1,1,1);