Skip to content
BytePatterns

Quarterly Sales as Columns

EasySQL#pivot#case-when#group-by~15m

Problem

A table sales(region, quarter, amount) holds one row per sale, with quarter a number from 1 to 4. Write a query that turns the quarters into columns: one row per region with columns region, q1, q2, q3 and q4, each holding that region's total for the quarter, or 0 when the region sold nothing in it. Sort by region.

Examples

Input:  sales = [("east", 1, 100), ("east", 2, 50), ("west", 1, 70), ("east", 1, 30), ("west", 4, 20)]
Output: [("east", 130, 50, 0, 0), ("west", 70, 0, 0, 20)]
Input:  sales = [("north", 3, 5), ("north", 3, 5), ("north", 3, 5)]
Output: [("north", 0, 0, 15, 0)]
Why:    every sale falls in quarter 3, the other three columns still appear as 0
Input:  sales = []
Output: []
Why:    edge case, no sales means no regions and no rows

Hints

0 / 3

Stuck on the idea rather than the code? WHERE and Filtering covers it.