Skip to content

Instantly share code, notes, and snippets.

@bxt
Created September 29, 2011 17:57
Show Gist options
  • Save bxt/1251421 to your computer and use it in GitHub Desktop.
Save bxt/1251421 to your computer and use it in GitHub Desktop.
MySQL - Calculate percentage of rows/records matching predicate using IF() and AVG
-- Tip: You can use IF() and AVG() together to get a percentage value
-- without doing subquerys
-- -
-- Basic usage:
-- SELECT AVG(IF( predicate ,100,0)) as percentage FROM table
-- Example:
-- -
SELECT
AVG(IF(f.mid,100,0)) as `percentage filed`
FROM
Nominations n, Movies m LEFT JOIN Filings f ON f.mid=m.id
WHERE
n.mid=m.id AND n.yid=3
-- -
-- Read:
-- "What portion of the Nominations with yid=3 have a Filing linked to their movie?"
-- -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment