I have a table named deposit, below
dep_id | deposit_amount | comp_id |
---|---|---|
1 | 100 | 1 |
2 | 100 | 1 |
3 | 100 | 1 |
When I run the query below I get the next updated table which is not what I want :
query = em.createNativeQuery("UPDATE deposit SET deposit_amount = (SELECT SUM(deposit_amount) - 50) WHERE comp_id = :comp_id");
query.setParameter("comp_id", comp_id);
The updated table after the above query
dep_id | deposit_amount | comp_id |
---|---|---|
1 | 50 | 1 |
2 | 50 | 1 |
3 | 50 | 1 |
But I want when I substract 50 or any amount it should get the sum of the columns and minus the amount from the sum not from each column. Below
dep_id | deposit_amount | comp_id |
---|---|---|
1 | 83.3 | 1 |
2 | 83.3 | 1 |
3 | 83.3 | 1 |
Because the sum is 300, and 300-50 = 250
Please how should I do this?
2
Answers
Using a common table expression, you can use this query. Get the total deposit amount per comp_id. Then join this new table (called total) to deposit on comp_id. Subtract 50 from the sum.
Sample:
You should compute deposit amount in a separate query, then join back your two tables on matching "comp_id" value
In your final query it should look like:
Check the demo here.