SQL
Performing Conditional Aggregation with CASE
Discover how to use `CASE` expressions within aggregate functions (like `SUM` or `COUNT`) to perform conditional aggregations, generating powerful summary reports.
SELECT
department,
SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) AS active_employees,
SUM(CASE WHEN status = 'Inactive' THEN 1 ELSE 0 END) AS inactive_employees
FROM
employees
GROUP BY
department;
How it works: This snippet uses the `CASE` expression inside the `SUM()` aggregate function to perform conditional counting. For each row, if the `status` matches 'Active', it contributes 1 to `active_employees`; otherwise, 0. This allows for summarizing data based on different conditions within a single query, providing flexible reporting.