Forum

Posted by rocko, June 17, 2024, 10:13 a.m.

Q13 Fast movie watchers vs slow movie watchers. Count isn't matching

Hi all, Below is my answer, but the count isn't matching. Can you please help me with the part that is missing. 

SELECT

    'slow_watcher' AS watcher_category,

    COUNT(*) AS count

FROM

    (

        SELECT

            customer_id,

            ROUND(AVG(EXTRACT(EPOCH FROM (return_ts - rental_ts)) / 86400)) AS avg_time_taken

        FROM

            rental

        WHERE

            return_ts IS NOT NULL

        GROUP BY

            customer_id

    ) AS data

WHERE

    avg_time_taken <= 5

UNION ALL

SELECT

    'fast_watcher' AS watcher_category,

    COUNT(*) AS count

FROM

    (

        SELECT

            customer_id,

            ROUND(AVG(EXTRACT(EPOCH FROM (return_ts - rental_ts)) / 86400)) AS avg_time_taken

        FROM

            rental

        WHERE

            return_ts IS NOT NULL

        GROUP BY

            customer_id

    ) AS data

WHERE

  avg_time_taken > 5



Expected : 

watcher_category | count
------------------+-------
 fast_watcher     |   112
 slow_watcher     |   487


I am getting : 

watcher_category count
slow_watcher 484
fast_watcher 115

thanks :)

Answers

 

Hello!

I see the issue is with your average function -  

  ROUND(AVG(EXTRACT(EPOCH FROM (return_ts - rental_ts)) / 86400)) AS avg_time_taken

Let's say a customer returns 2 movies, 1 in 2.2 days and other in 2.1 days. In this case these both movies were returned on 3rd day so we need to count this as 6 days as average of 3 days. Your function will assume this as 4.3 days with the average of 2.15 days then round it to 2 days.

You can use CEIL() before AVG() to achieve the same -

    CEIL(AVG(CEIL(EXTRACT(EPOCH FROM (return_ts - rental_ts)) / 86400))) AS avg_time_taken 
 
Use CEIL at the end because, 2.1 days need to be considered as 3 days.

I used 'Day' directly in EXTRACT() to achieve the same. Here's my function - 

    CEIL(AVG(EXTRACT(Day FROM (return_ts - rental_ts)))) AS avg_days_taken    

 

SQLPad user avatar

Shubham (6)

Aug. 16, 2024, 3 a.m.