Reputation: 557
How do you compare (< or >) the result of one column, against the result of another column of two select statements?
I need to get a list only of the sold out movies. To do this, I need to check if the number on the rented_movie_count on the first select statement is equal or greater than the number on the available_movie_count on the second select statement.
First Statement
result of the
select MOVIE_ID, count(MOVIE_ID) as rented_movies_count
from MOVIE_QUEUE
WHERE STATUS_ID=2
group by MOVIE_ID;
Second Statement
select MOVIE_ID, count(MOVIE_ID) as available_movie_count
from dvd
group by MOVIE_ID;
I am still very new to this and I am trying to learn, even suggestions about what kind of syntax (operators, expressions, etc) should I use will help at least point me on a a directions to do more research. Thanks in advance
Upvotes: 0
Views: 69
Reputation: 2787
Given your database structure, a possible solution would be
SELECT rented.MOVIE_ID
,rented_movies_count
,available_movie_count
FROM (
SELECT MOVIE_ID, count(MOVIE_ID) AS rented_movies_count
FROM MOVIE_QUEUE
WHERE STATUS_ID=2
GROUP BY MOVIE_ID
) rented
,(SELECT MOVIE_ID, count(MOVIE_ID) AS available_movie_count
FROM dvd
GROUP BY MOVIE_ID
) available
WHERE rented.movie_id = available.movie_id
AND rented_movies_count >= available_movie_count
;
I've set up an example on http://www.sqlfiddle.com/#!4/3fc59/11 to test. But I guess that's more or less what you've come up with.
But I somewhat doubt that your database structure is really optimal!? Do you really store more than one record for a singe movie_id
in the table dvd
?
Wouldn't it be more useful to have exactly one record per movie_id
in dvd
along with some movie attributes and store the rental status of the dvds in movie_queue.status_id
?
If movie_queue.status_id
is defined as say
Then your query would be much more easy:
SELECT MOVIE_ID
,count(case when status_id = 1 then 1 end) AS available_movie_count
,count(case when status_id = 2 then 1 end) AS rented_movies_count
FROM MOVIE_QUEUE
GROUP BY MOVIE_ID
HAVING count(case when status_id = 2 then 1 end) >= count(case when status_id = 1 then 1 end)
;
See for example http://www.sqlfiddle.com/#!4/13739/1
Upvotes: 1