PostgreSQL中的中位数、众数和平均数。

众数

postgres=# select mode() within group (order by id) as mode from t_test;
 mode
------
    2
(1 row)

中位数

当为偶数时,结果没有按数学上的定义,进行相加在除二。
官方文档1
官方文档2

postgres=# select percentile_disc(0.5) WITHIN GROUP (ORDER BY id) from t_test;
 percentile_disc
-----------------
               3
(1 row)

平均数

postgres=# select avg(id) from t_test;

测试表

postgres=# create table t_test(id int4);
CREATE TABLE
postgres=# insert into t_test(id) values(1),(2),(2),(3),(4),(5),(6),(2),(7),(4),(8),(2);
postgres=# select * from t_test order by id;
 id
----
  1
  2
  2
  2
  2
  3
  4
  4
  5
  6
  7
  8
(12 rows)
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐