SQL practice: Pivoting: Turning Rows Into Columns

Chapter 40 · 7 questions · included in full access

  1. Question 1 · easy

    For every branch that has orders, show branch_name and three counts: delivered, pending and cancelled. Order by branch_name.

    Solve it in your browser
  2. Question 2 · easy

    Write the same delivered count using COUNT with a CASE expression instead of FILTER. Show branch_name and delivered, ordered by branch_name.

    Solve it in your browser
  3. Question 3 · medium

    For 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.

    Solve it in your browser
  4. Question 4 · medium

    For 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.

    Solve it in your browser
  5. Question 5 · medium

    Show 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.

    Solve it in your browser
  6. Question 6 · hard

    Your pivot query hard-codes three order statuses. Someone adds a fourth status to the table. What happens to the query?

    Solve it in your browser
  7. Question 7 · hard

    Build 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.

    Solve it in your browser

These questions are part of full access.

The first chapters of every track are free. Full access is a one-time payment.

See pricing