Let's get started! The first method we're going to show allows you to put groups into separate rows.
Suppose we want to show the number of orders shipped to North America and the number of orders shipped to other places in separate rows, like this:
We can use the following query:
WITH orders_by_group AS (
WHEN ship_country IN ('USA', 'Canada', 'Mexico')
THEN 'North America'
END AS shipping_continent
COUNT(order_id) AS order_count
GROUP BY shipping_continent;
Inside the inner query, we select the
order_id and use the
CASE WHEN construction to classify orders based on the
ship_country column. The classification result is stored in a column named
shipping_continent, which is either
'North America' or
'Other'. You can define as many values as you want; you don't need to limit yourself to two.
In the outer query, we group all rows from the inner query by the
shipping_continent column and use the
COUNT(order_id) function to count matching orders. As a result, each group is shown in a separate row.