Mysql:计算连接表的中位数

时间:2018-04-06 13:37:16

标签: mysql join subquery median

我有2张桌子...... 每个TABLE1的记录在TABLE2上有多个分数,我需要从TABLE2获取每个TABLE1记录的中位数值

如何组合这两个查询?

简单加入查询:

SELECT *
  FROM `TABLE1` 
  LEFT JOIN `TABLE2` ON `TABLE2`.`table1_id` = `TABLE1`.`id`

中位数查询:

SET @rowindex := -1;
 SELECT
   AVG(g.scores)
FROM
   (SELECT @rowindex:=@rowindex + 1 AS rowindex,
           TABLE2.scores AS scores
    FROM TABLE2
    ORDER BY TABLE2.scores) AS g
WHERE
g.rowindex IN (FLOOR(@rowindex / 2) , CEIL(@rowindex / 2));

0 个答案:

没有答案