Forum

Posted by Tobias, April 29, 2022, 7:56 a.m.

Question 43

Why doesn't this approach work in question 43 but in 42 it does. Both questions are from my understanding quite similar. 

My Solution for Q43: 

with cr as 
(
  SELECT c.customer_id
      , case when count(r.rental_id) is Null then 0 else count(r.rental_id) end as count 
  FROM customer as c 
  left join rental as r on r.customer_id=c.customer_id
  where date(r.rental_ts)<= '2020-05-31' and date(r.rental_ts)>= '2020-05-01'
  group by c.customer_id


)
select case when count > 0 then 'rented' else 'never-rented' end as hass_rented
    , count(*) as count
From cr
group by hass_rented

Answers

Very good question Tobias!

The tricky part is how the DB engine executes your query (in what order).

In your query:

The where date ... clause ran first, then the case when is applied on the filtered results.

To fix your query:

You need to run the case when count... before the where clause is executed.

A simple trick to do that is to move the where condition to be part of the join condition (join always run before the where clause).

 

Here is an updated query (passed the online judge):

with cr as 
(
  SELECT c.customer_id
      , case when count(r.rental_id) is Null then 0 else count(r.rental_id) end as count 
  FROM customer as c 
  left join rental as r on r.customer_id=c.customer_id
and date(r.rental_ts)<= '2020-05-31' and date(r.rental_ts)>= '2020-05-01'
  group by c.customer_id

)
select case when count > 0 then 'rented' else 'never-rented' end as hass_rented
    , count(*) as count
From cr
group by hass_rented

 



hope it helps
--leon

Hi Leon,

For this part:  case when count(r.rental_id) is Null then 0 else count(r.rental_id) end as count

Can I rewrite it as:  

COUNT(CASE WHEN r.rental_id IS NOT NULL THEN r. rental_id  ELSE NULL END)?

Best

Ming

Luming, July 12, 2022, 11:59 p.m.

Yes @Luming, I actually prefer your code, much easier to read and understand.

Leon, July 13, 2022, 6:18 a.m.
SQLPad user avatar

Leon (949)

April 29, 2022, 8:41 a.m.