Instruction
Very well done! Let's move on to method two. This method shows different groups in separate columns.
Let's say we want to count the number of orders already shipped and the number of orders not yet shipped:
| orders_shipped | orders_pending |
|---|---|
| 809 | 21 |
Take a look at the query:
SELECT
COUNT(CASE
WHEN shipped_date IS NOT NULL
THEN order_id
END) AS orders_shipped,
COUNT(CASE
WHEN shipped_date IS NULL
THEN order_id
END) AS orders_pending
FROM orders;
In this technique, we use multiple COUNT(CASE WHEN...) or SUM(CASE WHEN...) statements in the query. Each statement is used to show the metric for a single group in a new column. We also need to name each column using the X AS alias construction.
In Method 1, groups were represented as rows and created with a single CASE WHEN statement. Here, they are represented as columns and created with separate aggregate function invocations. This is why Method 2 is typically a good choice for a small number of groups.
Exercise
Count the number of vegetarian and non-vegetarian products. Show two columns: non_vegetarian_count and vegetarian_count.
Hint: Non-vegetarian products have a category_id of 6 or 8.
Stuck? Here's a hint!
You can count non-vegetarian products in the following way:
COUNT(CASE
WHEN category_id IN (6, 8)
THEN product_id
END)



