Set Operations with GROUP BY
Set Operations with GROUP BY is a SQL statement in the Set Operations category. Each branch of a set operation can have its own GROUP BY. Then combine for a unified summary. The syntax is SELECT * FROM (SELECT col, COUNT(*) FROM table1 GROUP BY col) AS a UNION ALL SELECT * FROM (SELECT col, COUNT(*) FROM table2 GROUP BY col) AS b;. It returns aggregated set result. A typical example: SELECT department, employee_count, 'Current' AS period FROM (SELECT dept AS department, COUNT(*) AS employee_count FROM employees GROUP BY dept) AS current UNION ALL SELECT department, employee_count, 'Archived' FROM (SELECT dept AS department, COUNT(*) AS employee_count FROM terminated_employees GROUP BY dept) AS archived ORDER BY period, department; -- Combined department counts from current and archived employees A close relative is UNION, which combines results from two queries, removing duplicate rows. Each SELECT must have the same number of columns.