Forum

Posted by Abbas, July 13, 2023, 3:48 a.m.

44. In-demand vs not-in-demand movies

Could you please let me know where I am going wrong with my below query:

 

As my result gives in-demand:331

not-in-demand:355

whereas expected result not-in-demand:669

 

with cte as
(select f.film_id, count(r.rental_id) as counters from film f left join inventory i on f.film_id=i.film_id left join rental r on i.inventory_id=r.inventory_id
where r.rental_ts>='2020-05-01' and r.rental_ts<'2020-06-01' group by f.film_id)

select case when counters>1 then 'in-demand'
else 'not-in-demand'  end as demand_category,count(*) from cte
group by demand_category;

Answers

Hey Abbas,

Great question and very close, the trick is also include those in the film catalog but not even in inventory.

So whte where clause really have to be applied first otherwise the left join has no effect since the null results are filtered out (but we we want to keep for counting later on).

-Leon

SQLPad user avatar

Leon (949)

July 14, 2023, 10:25 a.m.