没有 UDF 是可能的,我知道有两种方法可以做到这一点。第一个使用两个选择和一个连接,第一个选择获取值和排名,第二个选择获取计数,然后连接它们。第二个使用 json 函数在一次选择中获取所有内容。它们都有点冗长,但它们可以工作并且相当快。
解决方案#1(两个选择和一个加入,一个获得计数,一个获得排名)
SELECT x.group_field,
avg(
if(
x.rank - y.vol/2 BETWEEN 0 AND 1,
value_field,
null
)
) as median
FROM (
SELECT group_field, value_field,
@r:= IF(@current=group_field, @r+1, 1) as rank,
@current:=group_field
FROM (
SELECT group_field, value_field
FROM table_name
ORDER BY group_field, value_field
) z, (SELECT @r:=0, @current:='') v
) x, (
SELECT group_field, count(*) as vol
FROM table_name
GROUP BY group_field
) y WHERE x.group_field = y.group_field
GROUP BY x.group_field;
解决方案 #2(使用 json 对象来存储计数并避免连接)
SELECT group_field,
avg(
if(
rank - json_extract(@vols, path)/2 BETWEEN 0 AND 1,
value_field,
null
)
) as median
FROM (
SELECT group_field, value_field, path,
@rnk := if(@curr = group_field, @rnk+1, 1) as rank,
@vols := json_set(
@vols,
path,
coalesce(json_extract(@vols, path), 0) + 1
) as vols,
@curr := group_field
FROM (
SELECT p.group_field, p.value_field, concat('$.', p.group_field) as path
FROM table_name
JOIN (SELECT @curr:='', @rnk:=1, @vols:=json_object()) v
ORDER BY group_field, value_field DESC
) z
) y GROUP BY group_field;