Last active
September 5, 2016 05:00
-
-
Save Sibirtsev/6f6a5cae63c4dd69a0f149ba1dccdcc1 to your computer and use it in GitHub Desktop.
Median in MySQL
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
SET @rownum := -1; | |
SET @quantile := 0.5; | |
SELECT | |
AVG(t.field) | |
FROM | |
( | |
SELECT | |
@rownum := @rownum + 1 AS rownum, | |
table.field AS field | |
FROM | |
table | |
ORDER BY table.field | |
) AS t | |
WHERE | |
t.rownum IN ( | |
CEIL(@rownum * @quantile), | |
FLOOR(@rownum * @quantile) | |
) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment