Created
September 29, 2011 17:57
-
-
Save bxt/1251421 to your computer and use it in GitHub Desktop.
MySQL - Calculate percentage of rows/records matching predicate using IF() and AVG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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