Skip to content

Instantly share code, notes, and snippets.

@brantfaircloth
Created December 11, 2009 01:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brantfaircloth/253908 to your computer and use it in GitHub Desktop.
Save brantfaircloth/253908 to your computer and use it in GitHub Desktop.
median and mode in mysql
  • Mode

      SELECT trimmed_len, COUNT(trimmed_len) AS mode FROM sequence GROUP BY trimmed_len ORDER BY mode DESC LIMIT 1;
    
  • Median

      CREATE TEMPORARY TABLE tmp (n INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, value VARCHAR(99) NOT NULL );
      INSERT INTO tmp (value) SELECT value FROM table ORDER BY 1;
      SELECT @count := COUNT(*) FROM tmp;
      SELECT DISTINCT value FROM tmp WHERE n IN (FLOOR((@count+1)/2), CEIL((@count+1)/2));
      DROP TEMPORARY TABLE tmp;
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment