Pivot Daily Sales by Region
Medium
SQLCASEGROUP BY
Problem
Schema: Sales(sale_date DATE, region VARCHAR, amount DECIMAL). Region is one of NA, EU, APAC.
Return one row per date with columns na, eu, apac, each holding the SUM of amount for that region that day (0 if missing).
Example 1
Input: Jan 1 NA 100, Jan 1 EU 50
Output: (Jan 1, 100, 50, 0)
Constraints
- Region values are limited to the three listed.
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
SQL
SELECT sale_date,
SUM(CASE WHEN region = 'NA' THEN amount ELSE 0 END) AS na,
SUM(CASE WHEN region = 'EU' THEN amount ELSE 0 END) AS eu,
SUM(CASE WHEN region = 'APAC' THEN amount ELSE 0 END) AS apac
FROM Sales
GROUP BY sale_date
ORDER BY sale_date;
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Pivot Daily Sales by Region interactively → ← All solutions