Question presented to candidate:
"Our sales table has one row per sale with a region, a quarter and an amount. Finance wants a report with one row per region and one column per quarter, Q1 to Q4, holding the total. Write that query. Then tell me what you would do if the list of quarters is not known in advance, and how the answer differs between PostgreSQL, SQL Server and SQLite."
What a strong answer should cover:
- Pivoting turns the distinct values of one column into output columns; the portable way is conditional aggregation:
GROUP BYthe row key and oneSUM(CASE WHEN quarter = 'Q1' THEN amount END)per column - Empty cells: without
ELSEthe cell is NULL, withELSE 0orCOALESCEit is 0; choose deliberately, and makeCOUNTversusSUMbehave right - The
FILTER (WHERE ...)clause (PostgreSQL, SQLite 3.30+) as a cleaner spelling of the same thing - Engine features: SQL Server and Oracle
PIVOT, PostgreSQLcrosstab()from thetablefuncextension; all need the column list written out - SQL needs the output columns at parse time, so a pivot over unknown values needs dynamic SQL generated from the data (or pivoting in the application); and the reverse, unpivot, with
UNION ALLorUNPIVOT
Clarifying questions expected:
- Is the set of pivot values fixed (four quarters) or does it grow with the data?
- Should a missing combination show 0 or be empty?
- Is the result for a human report (pivot in SQL or the BI tool) or for code (keep it long)?
Code / implementation expected: Yes β a conditional-aggregation pivot query; optionally the dynamic-SQL generator.
Schema used by the examples: