Skip to content

Instantly share code, notes, and snippets.

@Sibirtsev
Last active March 7, 2017 04:14
Show Gist options
  • Save Sibirtsev/9ba779c2dde371dd738287c770b33ba6 to your computer and use it in GitHub Desktop.
Save Sibirtsev/9ba779c2dde371dd738287c770b33ba6 to your computer and use it in GitHub Desktop.
SELECT AVG(t1.`value`) AS median_val FROM (
SELECT @rownum:=@rownum+1 AS `row_number`, d.`value`
FROM `data` d, (SELECT @rownum:=0) r
WHERE 1 -- use self where
ORDER BY d.`value`
) AS t1,
(
SELECT count(*) AS total_rows
FROM `data` d
WHERE 1 -- use self where
) AS t2
WHERE 1
-- 0.5 - median
AND t1.row_number IN ( floor((total_rows+1) * 0.5), floor((total_rows+2) * 0.5) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment