Interview Questions/SQL/Delivery Performance - On-Time vs Late per City per Month

Delivery Performance - On-Time vs Late per City per Month

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of deliveries. Each delivery has a city, a promised delivery date, an actual delivery date, and the package weight in kg. A delivery is considered on-time if the actual_date is less than or equal to the promised_date; otherwise it is late. Write a SQL query to find for each month and city: the total number of deliveries, the number of on-time deliveries, the number of late deliveries, and the total weight of all packages (rounded to 2 decimal places). Return the result ordered by month and city. Table: Deliveries

Column NameTypeDescription
idINTPrimary key
cityVARCHARDestination city
promised_dateDATEPromised delivery date
actual_dateDATEActual delivery date
weight_kgREALPackage weight in kilograms

Database Schema (Inferred)

Deliveries

Column NameExample Value
id1
cityMumbai
promised_date2023-06-05
actual_date2023-06-05
weight_kg2.5

Example

Deliveries

idcitypromised_dateactual_dateweight_kg
1Mumbai2023-06-052023-06-052.5
2Mumbai2023-06-122023-06-141
3Delhi2023-06-082023-06-073
4Delhi2023-06-202023-06-250.5
5Mumbai2023-07-032023-07-034
6Delhi2023-07-152023-07-162

Output

monthcitytotal_deliverieson_time_countlate_counttotal_weight_kg
2023-06Delhi2113.5
2023-06Mumbai2113.5
2023-07Delhi1012
2023-07Mumbai1104

Explanation:

Group by month (from promised_date) and city. A delivery is on-time if actual_date <= promised_date. Use CASE WHEN for conditional counting and SUM(weight_kg) for total weight.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Deliveries

idcitypromised_dateactual_dateweight_kg
1Mumbai2023-06-052023-06-052.5
2Mumbai2023-06-122023-06-141
3Delhi2023-06-082023-06-073
4Delhi2023-06-202023-06-250.5
5Mumbai2023-07-032023-07-034
6Delhi2023-07-152023-07-162

Output

monthcitytotal_deliverieson_time_countlate_counttotal_weight_kg
2023-06Delhi2113.5
2023-06Mumbai2113.5
2023-07Delhi1012
2023-07Mumbai1104