Pandasdrill

Level 6: From Excel and SQL Exercise 86 of 102

SQL CASE WHEN inside a count

A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.

The task

In SQL you would write `SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END)` and the same for cancelled. Return one row per customer with the columns `customer`, `completed` and `cancelled`, holding the number of orders with each status. Use 0 where a customer has none.

What this exercise teaches

crosstab(rows, columns) counts how often each pair occurs, which is exactly a set of conditional counts side by side. Combinations that never occur become 0, not a missing value. The same result comes from turning each condition into a 0/1 column and summing per customer.

A hint if you get stuck

You want one column per status value. crosstab counts the combinations of two columns and fills the gaps with 0.

Try it now, free, no account needed

Your first 8 exercises on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro unlocks every exercise, timed mode and the certificate.

Open this exercise

More exercises in From Excel and SQL