Perfect! Now that we know how to show metrics for multiple business objects in a single report, we would like to show order counts for each employee at Northwind. You might be tempted to write the following query:
SELECT
e.first_name,
e.last_name,
COUNT(*) AS orders_count
FROM orders o
JOIN employees e
ON o.employee_id = e.employee_id
GROUP BY e.first_name,
e.last_name;
The query seems fine at first sight, but it can actually produce incorrect results. Employees' first and last names may not be unique – imagine two employees that share the same name. In such a case, their orders will be grouped together, which is incorrect. Luckily, we can easily fix the query:
SELECT
e.employee_id,
e.first_name,
e.last_name,
COUNT(*) AS orders_count
FROM orders o
JOIN employees e
ON o.employee_id = e.employee_id
GROUP BY e.employee_id,
e.first_name,
e.last_name;
We've added the employee_id
column to the GROUP BY
and SELECT
clauses. Because employee IDs are unique, the query will now produce correct results.
Remember, you should always GROUP BY
unique columns that differentiate between various business objects.