Skip to content

Instantly share code, notes, and snippets.

@mente
Created January 9, 2015 09:44
Show Gist options
  • Save mente/fd077946565e1c685665 to your computer and use it in GitHub Desktop.
Save mente/fd077946565e1c685665 to your computer and use it in GitHub Desktop.
#Table
CREATE TABLE `departments` (
`in` int(11) unsigned NOT NULL,
`out` int(11) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
#Via JOIN
SELECT i.count + o.count as total, i.in
FROM
(
SELECT COUNT(*) count, `in`
FROM departments
GROUP BY `in`) i
LEFT JOIN
(SELECT COUNT(*) count, `out`
FROM departments
GROUP BY `out`) o ON i.in = o.out
ORDER BY total DESC LIMIT 1
#Via UNION
SELECT SUM(count) total, airport
FROM
((SELECT COUNT(*) count, `in` as airport
FROM departments
GROUP BY `in`) i
UNION ALL
(SELECT COUNT(*) count, `out` as airport
FROM departments
GROUP BY `out`) o) t
GROUP BY airport
ORDER BY total DESC
LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment