cswork / libraryOpen practice workspace

Coding questions · Meta

Calculate Daily Visibility Score for Each Shop

This question evaluates a candidate's ability to perform conditional aggregation and time-based grouping to compute derived metrics such as impressions, views, and a visibility ratio per shop and calendar day.

shop_events

user_idevent_timeevent_typeproduct_idshop_id
1012023-07-01impression550112
1012023-07-01view550112
1022023-07-01impression660212
1032023-07-01view770315
1042023-07-02impression550112
Scenario

The analytics team wants a daily visibility score for each shop, defined as views divided by impressions.

Question

Write a SQL query that, for every shop and calendar day, returns impressions, views, and visibility_ratio = views/impressions, ordered by event_date and shop_id.

Hints

Use CASE or FILTER clauses for conditional aggregation.

Daily Shop Visibility Ratio

Given a table of shop events, write a SQL query that, for every shop and calendar day, returns the number of impressions, the number of views, and a visibility_ratio defined as views divided by impressions. If impressions is 0, visibility_ratio should be NULL. Order the result by event_date and shop_id.

Table shop_events

columntypeconstraints
user_idINTEGER
event_timeDATE
event_typeVARCHAR
product_idINTEGER
shop_idINTEGER

Sample data:

event_timeevent_typeproduct_idshop_iduser_id
2023-07-01impression550112101
2023-07-01view550112101
2023-07-01impression660212102
2023-07-01view770315103
2023-07-02impression550112104

Expected output

For each shop and date, return counts of impressions and views and the visibility_ratio (views divided by impressions). If impressions is 0, visibility_ratio is NULL. Results are ordered by event_date then shop_id.

event_dateimpressionsshop_idviewsvisibility_ratio
2023-07-0121210.5
2023-07-010151NULL
2023-07-0211200

Hints

  1. Use CASE expressions for conditional aggregation (or FILTER if your SQL dialect supports it).
  2. Cast counts to a decimal type and use NULLIF(impressions, 0) in the denominator to avoid division by zero.