SQL

SQL 라이브 코테 뽀개기 Day3: Laptop vs. Mobile Viewership

sawo11 2025. 3. 6. 18:07

This is the same question as problem #3 in the SQL Chapter of Ace the Data Science Interview!

Assume you're given the table on user viewership categorised by device type where the three types are laptop, tablet, and phone.

Write a query that calculates the total viewership for laptops and mobile devices where mobile is defined as the sum of tablet and phone viewership. Output the total viewership for laptops as laptop_reviews and the total viewership for mobile devices as mobile_views.

Effective 15 April 2023, the solution has been updated with a more concise and easy-to-understand approach.

viewership Table

Column NameType
user_id integer
device_type string ('laptop', 'tablet', 'phone')
view_time timestamp

viewership Example Input

user_id device_type view_time
123 tablet 01/02/2022 00:00:00
125 laptop 01/07/2022 00:00:00
128 laptop 02/09/2022 00:00:00
129 phone 02/09/2022 00:00:00
145 tablet 02/24/2022 00:00:00

Example Output

laptop_views mobile_views
2 3
-- 방법1: SUM, CASE WHEN 사용하기
SELECT 
  SUM(CASE WHEN device_type = 'laptop' THEN 1 ELSE 0 END) laptop_views,
  SUM(CASE WHEN device_type IN ('tablet', 'phone') THEN 1 ELSE 0 END) mobile_views
FROM viewership

-- 방법2: COUNT, FILTER 사용하기
SELECT 
  COUNT(*) FILTER (WHERE device_type = 'laptop') AS laptop_views,
  COUNT(*) FILTER (WHERE device_type IN ('tablet', 'phone'))  AS mobile_views 
FROM viewership;
  • FILTER(WHERE ...)
    • PostgreSQL에서만 사용 가능