Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Method One
2. Method 1 – explanation
Method Two
Method Three
Summary

Instruction

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:

shipping_continent order_count
North America 180
Other 650

We can use the following query:

WITH orders_by_group AS (
  SELECT 
    order_id,
    CASE
      WHEN ship_country IN ('USA', 'Canada', 'Mexico')
        THEN 'North America'
      ELSE 'Other' 
    END AS shipping_continent
  FROM orders
)
SELECT
  shipping_continent,
  COUNT(order_id) AS order_count
FROM orders_by_group
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.

Exercise

Count the orders processed by employees from the 'WA' region and by all other employees. Show two columns: employee_region (either 'WA' or 'Not WA'), and order_count.

Stuck? Here's a hint!

In the inner query, you'll have to join the employees and orders tables.