Where the Money Sits

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

Domain
SQL
Difficulty
medium
Seniority
L4
Asked in
LinkedIn

Problem

The finance team is building a per-team cost summary. For each team, report how many of its allocations fall in the 'compute' category, alongside the total cost across every allocation the team owns, whatever the category.

Every team carries a cost, and some of it is what keeps the servers running.

Tables

cost_allocs

Columns: alloc_id INTEGER, team_name TEXT, svc_name TEXT, region TEXT, amount REAL, period TEXT, acct_id TEXT, category TEXT

cost_allocs: 10 of 200 rows
alloc_idteam_namesvc_nameregionamountperiodacct_idcategory
129data-engS3us-west-283.212026-02acct-101storage
158ml-teamRDSeu-west-1156.422026-03acct-102network
187frontendLambdaap-south-1229.632026-04acct-103database
216backendBigQueryus-central1-120.52026-05acct-104ml
245devopsCloudFronteurope-west1376.052026-06acct-105other
274securityEKSap-southeast-1449.262026-07acct-106compute
303mobileSQSeu-central-1522.472026-08acct-107storage
332PlatformEC2us-east-1595.682026-09NULLnetwork
361DATA-ENGS3us-west-2668.892026-01acct-109database
390platformRDSeu-west-1742.12026-02acct-110ml

Expected output

First 5 of 16 rows
team_namecompute_counttotal_cost
DATA-ENG0179212.3
Platform7177568.9
backend6161170.57
data-eng0175178.1
legal1100

Worked solution and explanation

What this problem really is

Beneath the finance-dashboard framing, this is two aggregates riding one scan over the same rows: a filtered count of compute allocations sitting next to an unfiltered sum of every dollar. Anyone can sum a column. The move that separates candidates is keeping the 'compute' condition inside the aggregate instead of the WHERE clause. Push it into a WHERE and total_cost silently drops every non-compute row, so finance sees a spend number that is too small with no error to explain it.


Break down the requirements

Step 1: Group by team

GROUP BY team_name produces one row per team, so both metrics land on the same line of the report.

Step 2: Count compute allocations

SUM(CASE WHEN category = 'compute' THEN 1 ELSE 0 END) counts only the compute allocations while still visiting every row. Teams with no compute rows get 0 instead of vanishing.

Step 3: Sum total cost

SUM(amount) runs over the exact same grouped rows, unfiltered, so the total reflects the whole team's spend across every category.


The solution

Mixed conditional and unconditional aggregation
SELECT
    team_name,
    SUM(CASE WHEN category = 'compute' THEN 1 ELSE 0 END) AS compute_count,
    SUM(amount) AS total_cost
FROM cost_allocs
GROUP BY team_name

Common follow-up questions