Answer the question
In order to leave comments, you need to log in
How to get the difference between a value in a table and the sum of values from another table?
Suppose there is a user table with id, numberOfBooks, idOfLibrary and a library table with id, totalNumberOfBooks.
Those. there are people assigned to a certain library, they take books only from it. You need to find out how many books are left in the libraries, i.e. the difference between totalNumberOfBooks and the sum of NumberOfBooks of all users assigned to the library.
Answer the question
In order to leave comments, you need to log in
select
t1.id,
t1.totalNumberOfBooks - t2.userBooks
from library t1
join
(
select
idOfLibrary,
sum(numberOfBooks) as userBooks
from user
group by idOfLibrary
) t2 on t2.idOfLibrary = t1.idOfLibrary
something like this
SELECT t2.id, t2.totalNumberOfBooks-t1.vidano_knig ostatok
from (select idOfLibrary, sum(numberOfBooks) vidano_knig from user group by idOfLibrary) t1
join library t2 on t2.id=t1.idOfLibrary
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question