Aisle by aisle
- O(n) · Medium
- Full plan
- SQL
- grouping
- conditionals
Problem
The owner is about to walk the store with the restock sheet in hand, and wants to know what's waiting in each aisle: how many products each category has, and how many of them are out of stock, with the stock at 0. Show the category, then how many products it has, then how many are out of stock. Every category goes on the sheet: one with everything in place isn't left off: it gets a 0.
A hint: if every product had a 1 next to it when it's out of stock and a 0 when it isn't, all that would be left is adding them up.
What it has to return
These rows, in any order
| category | how_many | out_of_stock |
|---|---|---|
| Accessories | 3 | 1 |
| Audio | 2 | 1 |
| Devices | 2 | 0 |
| Displays | 1 | 0 |
This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.
You start with this
SQL
SELECT category,
COUNT(*) AS how_many
FROM products
GROUP BY category;It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(n) challenges
- Averages that mean somethingSQL · grouping · joins
- Bunched up or spread outSQL · grouping · joins · sorting
- Chairs for parents' nightSQL · grouping · joins · sorting
- How many payrolls does it cover?SQL · grouping · joins · decimals
- Not the priciest, not the biggestSQL · grouping · joins
- Pages carried homeSQL · grouping · joins · decimals