AlgoMaster Logo

Exercise: Pivoting and Unpivoting Data

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

Write a query using conditional aggregation that pivots payments into one row per user with columns completedrefunded, and failed showing the count of payments in each status.

SQL

Expected Query

Expected Output

Exercise 2

Hard

Using CROSS JOIN LATERAL with VALUES, write a query that unpivots the payments table to produce one row per (payment_id, metric, value) triple, where metric is either 'amount' or 'refund_amount'. Filter to payments made by user 3.

SQL

Expected Query

Expected Output