Friday Spending Analysis

A hard SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
hard
Seniority
L3
Asked in
IBM

Problem

Each row of transactions is one purchase with its total_amount and transaction_date, and only the Fridays dated in January, February and March count here. Report the average Friday amount for each week of that quarter, with the week as an integer counted from the year's first Monday (the January days before it fall in week 0).

Friday spending during Q1.

Tables

transactions

Columns: transaction_id INTEGER, user_id INTEGER, product_id INTEGER, quantity INTEGER, total_amount REAL, transaction_date TEXT

transactions: 10 of 200 rows
transaction_iduser_idproduct_idquantitytotal_amounttransaction_date
10671971001223.462026-02-02
11342941050336.932026-03-03
12013911099450.42026-04-04
12684881148563.872026-05-05
13355851197002026-06-06
14026821246290.812026-07-07
146977912953104.282026-08-08
153687613444117.752026-09-09
160397313935-452026-01-10
1670107014421144.692026-02-11

Expected output

First 5 of 7 rows
week_numberavg_amount
1494.91
21343.52
536.93
7265.92
81114.53

Worked solution and explanation

What this is really asking

This is date-part bucketing wearing a spending-report costume. The table stores a date and nothing else, so the weekday, the month and the week all have to be pulled out of transaction_date. Anyone can write the average. What separates candidates is the quarter fence: week 13 starts on 30 March and its Friday is 3 April, so fence the quarter by week number and an April Friday walks into the result. The quieter trap is the week itself: it comes back as zero-padded text, and it counts from the year's first Monday, not ISO.


Build it in three moves

Step 1: Keep only Fridays

strftime('%w', transaction_date) returns the weekday as text with Sunday as '0', so Friday is '5'. Compare text to text and the filter is unambiguous on every engine.

Step 2: Fence the quarter by month

strftime('%m', transaction_date) IN ('01', '02', '03') fences the first quarter by the calendar, which is the definition the question uses. A bound like week 13 or lower looks equivalent and keeps the 3 April Friday.

Step 3: Bucket by week_number and average

%W is the Monday-based week of year, and it comes back as text: '07'. Wrapping it in CAST(... AS INTEGER) is what makes week_number the integer 7 the question asks for. Name it once and group by that name, then AVG(total_amount) gives the mean per week, not the sum.


Friday average per week
SELECT
    CAST(strftime('%W', transaction_date) AS INTEGER) AS week_number,
    AVG(total_amount) AS avg_amount
FROM transactions
WHERE strftime('%w', transaction_date) = '5'
  AND strftime('%m', transaction_date) IN ('01', '02', '03')
GROUP BY week_number;

Where the interviewer goes next

Common follow-up questions