SQL Quest › SQL Interview Questions › Window Functions

Each Merchant's Share of Its Category

MediumFreeQuerying BasicsWindow FunctionsSubqueries & CTEsJoins

Percent-of-parent. Challenge 276 asked for each category's share of the WHOLE ledger and a scalar subquery supplied the denominator. This asks for each merchant's share of ITS OWN CATEGORY, and the denominator is now different on every row — one grand total will not do.

SUM(x) OVER (PARTITION BY category) is the tool: it computes the category's total and keeps the merchant row, instead of collapsing it the way a GROUP BY would. Aggregate to one row per merchant in a CTE first, then window over that.

Return category, name, merchant_spend (rounded to 2 decimals), category_spend (the partition total, rounded to 2 decimals) and pct_of_category (100.0 × merchant ÷ category, rounded to 2 decimals). All 25 merchants. Order by category ascending, then pct_of_category descending, then name ascending.

Round at the end, not inside the window — rounding the inputs and then dividing gives a slightly different number.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect". Free accounts get 10 free challenge solves, and this can be one of them.

Schema

transactions

txn_idaccount_idamounttxn_atmerchant_idlatlngstatus
1149151.842026-03-04T12:39:39.078Z2440.342-74.4092completed
22110.722026-03-04T13:04:50.641Z752.936613.3229completed
335158.782026-03-04T13:27:15.528Z2552.739713.3134completed

merchants

merchant_idnamecategorycountryrisk_tier
1BigBox MartGroceryTRhigh
2Quick StopElectronicsJPhigh
3Aurora CafeTravelTRhigh

Expected output: Clothing Flux Online 19515.31 68549.73 28.47; Clothing Vespa Apparel 13206.35 68549.73 19.27; ...

Hint

The hint for this one spells out most of the query, so it stays in the editor. Reach for SELECT, Window Functions, PARTITION BY, and open the hint there if you stall.

Concepts

SELECT Window Functions PARTITION BY CTE JOIN ROUND Window Functions + CTE

Practise the topic: SQL practice questions · Window function practice · CTE practice · JOIN practice

Read the concept: SQL running total

The trap to watch for: Average of averages

In these company practice sets

Capital One · Stripe · Goldman Sachs

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Preparing for Capital One? How the CodeSignal data analyst assessment works.

Related questions

Running Total of OrdersMedium · FreeTop 3 Merchants Per Category by SpendMedium · FreeBusiest Merchants, and What a Tie Does to the RankMedium · FreeRunning Total of Daily Card SpendMedium · FreeSalary Percentile RankingHard · ProFirst and Last Order per CustomerHard · Pro

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test