Skip to content

Instantly share code, notes, and snippets.

@Sibirtsev
Last active September 5, 2016 05:00
Show Gist options
  • Save Sibirtsev/6f6a5cae63c4dd69a0f149ba1dccdcc1 to your computer and use it in GitHub Desktop.
Save Sibirtsev/6f6a5cae63c4dd69a0f149ba1dccdcc1 to your computer and use it in GitHub Desktop.
Median in MySQL
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