You need to enable JavaScript to run this app. MySQL无原生MEDIAN函数时分组计算中位数的子查询适配问题
优惠活动
大模型
产品
解决方案
定价
更多

MySQL无原生MEDIAN函数时分组计算中位数的子查询适配问题

无内置MEDIAN函数时,按城市分组计算中位数的子查询匹配问题

复现用的测试表与样例数据

CREATE TABLE IF NOT EXISTS `test` (
  `t_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `t_city` varchar(64) NOT NULL,
  `t_category` enum('cat1','cat2') NOT NULL,
  `t_type` enum('type1','type2') NOT NULL,
  `t_num` int(8) NOT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

INSERT INTO `test` (`t_id`, `t_city`, `t_category`, `t_type`, `t_num`) VALUES
(1, 'New York', 'cat1', 'type1', 1056),
(2, 'New York', 'cat1', 'type1', 3756),
(3, 'London', 'cat1', 'type2', 3456),
(4, 'New York', 'cat1', 'type2', 5756),
(5, 'London', 'cat1', 'type2', 3777),
(6, 'New York', 'cat2', 'type1', 3756),
(7, 'New York', 'cat2', 'type1', 3756),
(8, 'London', 'cat2', 'type1', 3777),
(9, 'New York', 'cat2', 'type2', 4556),
(10, 'Berlin', 'cat1', 'type2', 1556),
(11, 'Berlin', 'cat2', 'type2', 9756),
(12, 'London', 'cat1', 'type2', 1756);

当前写好的查询语句

因为所用的MySQL版本没有内置的MEDIAN聚合函数,现在靠嵌套子查询手动实现中位数计算,整段SQL如下:

SELECT "cat1" as st_category, "type2" as st_type, t_city as st_name, 
(
  SELECT (ROUND(AVG(dd.t_num) / 10) * 10) as median
  FROM (
    SELECT d.t_num, @rownum:=@rownum+1 as `row_number`, @total_rows:=@rownum
    FROM test as d, (SELECT @rownum:=0) as r
    WHERE d.t_num is NOT NULL
      AND `t_category` = "cat1" 
      AND `t_type` = "type2" 
      AND `t_city` = "XXXXX"  -- 城市过滤条件占位符,取值待确定
    ORDER BY d.t_num
  ) as dd
  WHERE dd.row_number IN ( FLOOR((@total_rows+1)/2), FLOOR((@total_rows+2)/2) )
) as st_median,
COUNT(t_num) as st_count
FROM `test` 
WHERE `t_category` = "cat1" 
  AND `t_type` = "type2"
  AND t_city in ("London", "New York")
GROUP BY t_city
ORDER BY st_name ASC

碰到的卡点

嵌套的中位数计算子查询里,t_city等值过滤条件的占位符XXXXX不知道该填什么内容,才能让计算逻辑匹配外层的分组规则,让各城市对应的中位数返回正确值,而不是全为NULL。

现在跑出来的实际结果

执行当前SQL,所有分组的中位数字段都是NULL,完全不符合预期:

+-------------+---------+----------+-----------+----------+
| st_category | st_type |  st_name | st_median | st_count |
+-------------+---------+----------+-----------+----------+
|        cat1 |   type2 |   London |    (null) |        3 |
|        cat1 |   type2 | New York |    (null) |        1 |
+-------------+---------+----------+-----------+----------+

想要达到的预期输出

调整子查询的匹配逻辑后,最终需要拿到按城市分组、精度取到十位整数的计算结果:

+-------------+---------+----------+-----------+----------+
| st_category | st_type |  st_name | st_median | st_count |
+-------------+---------+----------+-----------+----------+
|        cat1 |   type2 |   London |      3460 |        3 |
|        cat1 |   type2 | New York |      5760 |        1 |
+-------------+---------+----------+-----------+----------+

内容的提问来源于stack exchange,提问作者Csala AB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.31 22:15:04