cswork / libraryOpen practice workspace

Coding questions · Meta

Generate Daily Unique User Views for Each Shop

This question evaluates a candidate's ability to perform data manipulation and aggregation using SQL (and optionally Python), focusing on counting unique users per shop by calendar date and handling date-based filtering.

shop_views

+---------+---------+---------------------+
| user_id | shop_id | view_time           |
+---------+---------+---------------------+
| 101     | 1       | 2023-05-01 10:00:00 |
| 102     | 1       | 2023-05-01 11:12:00 |
| 101     | 2       | 2023-05-02 09:35:00 |
| 103     | 1       | 2023-05-02 14:00:00 |
| 104     | 3       | 2023-05-02 15:32:00 |
+---------+---------+---------------------+
Scenario

The commerce team wants a daily report of how many unique users saw each shop in the last 7 days.

Question

Write SQL to return, for every shop_id and calendar date in the past 7 days, the number of unique users who viewed that shop.

Hints

Use DATE_TRUNC or CAST to day, DISTINCT user_id, and filter on current_date-7.

Daily unique shop views for the last 7 days

You are given a table shop_views that records when users view shops. Write SQL to return, for every shop_id and each calendar date from 2025-05-26 through 2025-06-01 (inclusive), the number of unique users who viewed that shop on that date. Include dates with zero views for each shop.

Table shop_views

columntypeconstraints
user_idINTEGERNOT NULL
shop_idINTEGERNOT NULL
view_timeTIMESTAMPNOT NULL

Sample data:

shop_iduser_idview_time
11012025-05-30 10:00:00
11022025-05-30 11:12:00
21012025-05-31 09:35:00
11032025-06-01 14:00:00
31042025-06-01 15:32:00

Expected output

One row per shop_id per calendar date between 2025-05-26 and 2025-06-01 (inclusive), with the count of distinct users who viewed that shop on that date. Include dates with zero views. Columns: shop_id (INTEGER), view_date (DATE), unique_user_views (INTEGER).

shop_idunique_user_viewsview_date
102025-05-26
102025-05-27
102025-05-28
102025-05-29
122025-05-30
102025-05-31
112025-06-01
202025-05-26
202025-05-27
202025-05-28
202025-05-29
202025-05-30
212025-05-31
202025-06-01
302025-05-26
302025-05-27
302025-05-28
302025-05-29
302025-05-30
302025-05-31
312025-06-01

Hints

  1. Truncate timestamps to the calendar day (e.g., view_time::date or CAST(view_time AS DATE)).
  2. Count DISTINCT user_id per shop_id and per date.
  3. Generate a calendar date series from '2025-05-26' to '2025-06-01' and LEFT JOIN it to the aggregated results to include dates with zero views.