SQL · medium
Asked in BI Developer interviews, in the SQL round.
Use conditional aggregation: MAX(CASE WHEN metric='x' THEN value END).
Conditional aggregation. One CASE per output column, wrapped in an aggregate so the group collapses to a single row.
SELECT
user_id,
MAX(CASE WHEN metric = 'sessions' THEN value END) AS sessions,
MAX(CASE WHEN metric = 'orders' THEN value END) AS orders,
MAX(CASE WHEN metric = 'revenue' THEN value END) AS revenue
FROM user_metrics
GROUP BY user_id;
MAX is the usual choice because each (user, metric) pair is expected to appear once; if a metric can appear several times, say whether SUM or the latest value is correct, because the aggregate is the business rule. This works in every database. Postgres has crosstab and SQL Server has PIVOT, but the column list is still fixed at write time; a pivot with an unknown set of metrics needs dynamic SQL or is done in the application.
CASE inside an aggregate pattern and can say why the aggregate is there.GROUP BY, which gives one row per input row with mostly NULLs.