如何计算每个代码的每年中位数。 下面是mysql表:
tbl_sales:
+-----+------+------+------+
| cod | cant | mont | year |
+-----+------+------+------+
| 432 | 1 | 10 | 2012 |
| 432 | 2 | 10 | 2012 |
| 432 | 4 | 10 | 2012 |
| 432 | 2 | 3 | 2012 |
| 432 | 3 | 2 | 2016 |
| 432 | 2 | 1 | 2016 |
| 432 | 8 | 8 | 2017 |
+-----+------+------+------+
手动计算中位数:
+------+---+---+---+---+---+---+---+---+---+----+----+----+-------+
| year | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | TOTAL |
+------+---+---+---+---+---+---+---+---+---+----+----+----+-------+
| 2012 | | | 2 | | | | | | | 7 | | | 9 |
| 2016 | 2 | 3 | | | | | | | | | | | 5 |
| 2017 | | | | | | | | 8 | | | | | 8 |
+------+---+---+---+---+---+---+---+---+---+----+----+----+-------+
MEDIAN (5,8,9) = 8
如何以这种方式显示sql:432 => 8
谢谢!
答案 0 :(得分:0)
查询的内核(显然是?):
SELECT year,SUM(cant) total FROM my_table GROUP BY year ORDER BY year;
从这里开始,我将在应用程序代码中处理其余部分。您可以在SQL中计算中位数,但不能在数据库上没有进一步点击,当您已经拥有执行计算所需的所有信息(行数和中间行的值)时,这似乎很乏味在这个结果中。