Pulling it all together
WITH
current_staff AS (
SELECT *
FROM person
WHERE active
AND (
leaving_date IS NULL
OR leaving_date >= CURRENT_DATE
)
AND (start_date <= CURRENT_DATE)
),
country_headcount AS (
SELECT o.country, count(*) AS headcount
FROM current_staff s
JOIN office o ON (s.office_id = o.id)
GROUP BY 1
)
SELECT ch.country, o.city, count(*), ch.headcount AS country_total
FROM current_staff cs
JOIN office o ON (cs.office_id = o.id)
JOIN country_headcount ch ON (o.country = ch.country)
GROUP BY 4, 1, 2
ORDER BY 4 DESC, 1, 3 DESC, 2;