cswork / libraryOpen practice workspace

Coding questions · Meta

Calculate Shop Visibility Ranking in Search Results

This question evaluates SQL data-manipulation skills including time-windowed aggregations, computation of derived visibility metrics, and ranking operations over event-level impression data.

shop_impressions

+------------+---------+----------+--------+
| date       | shop_id | position | clicks |
+------------+---------+----------+--------+
| 2024-06-01 | 101     | 1        | 45     |
| 2024-06-01 | 102     | 3        | 12     |
| 2024-06-02 | 101     | 2        | 30     |
| 2024-06-02 | 103     | 1        | 18     |
| 2024-06-03 | 101     | 1        | 55     |
+------------+---------+----------+--------+
Scenario

An e-commerce marketplace wants to measure how prominently each shop is shown in search results so that marketing can reward high-visibility sellers.

Question

Given table shop_impressions(date, shop_id, position, clicks), write a SQL query that

Calculates each shop’s average daily visibility score defined as 1/position over the past 7 days.

Ranks shops by that average visibility (highest first) and returns shop_id, avg_visibility, rank.

Hints

Use window or aggregation over a 7-day rolling window; remember to filter by the latest date available.

Rank Shops by 7-Day Average Visibility Score

You are given a table shop_impressions(date, shop_id, position, clicks) that records, for each day, where a shop appeared in search results and how many clicks it received. Define a shop's daily visibility score as 1/position for that row.

Write a SQL query that:

  1. Uses the latest date in the table as the end of a 7-day window.
  2. For that 7-day period, calculates each shop's average daily visibility score as AVG(1.0/position) over all its rows in the window.
  3. Ranks shops by this average visibility in descending order.

Return columns: shop_id, avg_visibility, rank.

Table shop_impressions

columntypeconstraints
dateDATE
shop_idINTEGER
positionINTEGER
clicksINTEGER

Sample data:

clicksdatepositionshop_id
452024-06-011101
122024-06-013102
302024-06-022101
182024-06-021103
552024-06-031101

Expected output

Using the latest date in the data (2024-06-03), consider the 7-day period from 2024-05-28 to 2024-06-03 (inclusive). For each shop, compute avg(1.0/position) over all rows in that window, then rank shops by this avg_visibility in descending order. Based on the sample data, shop 103 has visibility 1.0, shop 101 has average visibility (1 + 0.5 + 1) / 3 = 0.833333, and shop 102 has average visibility 1/3 ≈ 0.333333.

avg_visibilityrankshop_id
11103
0.8333332101
0.3333333102

Hints

  1. First identify the latest date in the table and build a 7-day window ending on that date.
  2. Aggregate by shop_id to compute AVG(1.0/position), then use a window function like RANK() to rank shops by this average in descending order.