SQL practice: Pivoting: Turning Rows Into Columns
Chapter 40 · 7 questions · included in full access
Question 1 · easy
Solve it in your browserFor every branch that has orders, show branch_name and three counts: delivered, pending and cancelled. Order by branch_name.
Question 2 · easy
Solve it in your browserWrite the same delivered count using COUNT with a CASE expression instead of FILTER. Show branch_name and delivered, ordered by branch_name.
Question 3 · medium
Solve it in your browserFor each region, show total revenue from Delivered orders only, in a column named delivered_revenue, alongside region. Revenue is quantity times unit_price from order_items. Order by region.
Question 4 · medium
Solve it in your browserFor each branch show branch_name, revenue from orders before 1 March 2024 as jan_feb, and revenue from 1 March onwards as mar_on. Use 0 rather than NULL where there is nothing. Order by branch_name.
Question 5 · medium
Solve it in your browserShow one row per product category with the number of ACP-sheet-thickness bands: thin_3mm for thickness 3, standard_4mm for 4, and thick_6mm for 6. Show category too, ordered by category.
Question 6 · hard
Solve it in your browserYour pivot query hard-codes three order statuses. Someone adds a fourth status to the table. What happens to the query?
Question 7 · hard
Solve it in your browserBuild a monthly cohort retention grid for orders. In first_orders, find each customer's first order month as cohort_month. In activity, join orders and calculate month_number as the number of elapsed months between cohort_month and order_date: (extract(year from o.order_date) - extract(year from f.cohort_month)) * 12 + (extract(month from o.order_date) - extract(month from f.cohort_month)). Return cohort_month formatted as 'YYYY-MM', cohort_size (total distinct customers in that cohort), and distinct active customer counts for month offsets 0, 1, 2, and 3 as m0, m1, m2, and m3 using FILTER. Order by cohort_month.
These questions are part of full access.
The first chapters of every track are free. Full access is a one-time payment.
See pricing