在mysql

时间:2018-12-10 21:52:41

标签: mysql mysql-function

我正在尝试在MySQL中创建一个聚合函数MEDIAN(),如MIN(),MAX(),AVG(),该函数将输入的列名或具有所需列值的字符串作为输入。

我无法理解MySQL自定义函数的局限性,如果有人可以帮助我找出实现方法,那将非常有帮助。

示例:

MySQL表具有2列(ID,数字)

+----+-----+
| id | num |
+----+-----+
|  1 |   5 |
|  1 |   6 |
|  1 |   7 |
|  2 |   1 |
|  2 |   3 |
|  2 |   5 |
+----+-----+

SELECT id, MEDIAN(num) as median
FROM table
GROUP BY id;

OR

SELECT id, MEDIAN(GROUP_CONCAT(num SEPARATOR ',') as median
FROM table
GROUP BY id;

预期输出为

+----+--------+
| id | median |
+----+--------+
|  1 |      6 |
|  2 |      3 |
+----+--------+

2 个答案:

答案 0 :(得分:0)

User defined aggregate stored functions在MariaDB-10.3.3中添加

MySQL可以执行聚合函数,但是在SQL中不能。他们需要一个[UDF(共享库实现)](https://dev.mysql.com/doc/refman/5.7/en/create-function-udf.html}

答案 1 :(得分:0)

没有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;