Conditional Aggregation Multiple Metrics

Compute multiple metrics in a single pass using conditional aggregation with CASE inside SUM for pivoted reporting.

SqlData Integrity

Code

sqlsnippet
9 lines
SELECT
  region,
  SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active_count,
  SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) AS inactive_count,
  SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_count,
  COUNT(*) AS total_count
FROM accounts
GROUP BY region
ORDER BY region;

How it works

What runs is SELECT, with accounts as the object involved.

Breaking the statements into their working parts: COUNT, SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

Run the statement against the accounts table.

Statements that matter

SELECT
  region,
  SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active_count,
  SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) AS inactive_count,
  SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_count,
  COUNT(*) AS total_count
FROM accounts
GROUP BY region
ORDER BY region;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`accounts`.