advancedJOINs — INNER, LEFT, RIGHT, FULL, SELF, CROSS
You need a report showing all employees and their total order amounts this year. Employees with no orders should show 0. How do you write this?
Use LEFT JOIN with COALESCE: SELECT e.emp_id, e.first_name || ' ' || e.last_name AS name, COALESCE(SUM(o.amount), 0) AS total_orders, COUNT(o.order_id) AS order_count FROM employees e LEFT JOIN orders o ON e.emp_id = o.emp_id AND EXTRACT(YEAR FROM o.order_date) = 2024 GROUP BY e.emp_id, e.first_name, e.last_name ORDER BY total_orders DESC. Key points: 1) LEFT JOIN ensures all employees appear. 2)
This is a Pro chapter
Sign in, then upgrade to Pro or Power to unlock this and the full Databases Mastery library.
You need a report showing all employees and their total order amounts this year. Employees with no orders should show 0. How do you write this?