简体   繁体   English

如何使用Postgres窗口函数按属性查找中位数?

[英]How to find median by attribute with Postgres window functions?

I use PostgreSQL and have records like this on groups of people: 我使用PostgreSQL并在一群人上有这样的记录:

name    | people | indicator
--------+--------+-----------
group 1 | 1000   | 1 
group 2 | 100    | 2
group 3 | 2000   | 3

I need to find the indicator for the median person . 我需要找到中位人士indicator The result should be 结果应该是

group 3 | 2000   | 3

If I do 如果我做

select median(name) over (order by indicator) from table1

It will be group 2 . 这将是group 2

Not sure if I can select this with a window function. 不知道我是否可以使用窗口功能选择它。

Generating 1000/2000 rows per record seems impractical, because I have millions of people in the records. 每条记录生成1000/2000行似乎是不切实际的,因为记录中有数百万人。

Find the first cumulative sum of people greater than the median of total sum: 查找大于总和中位数的人的第一个累积总和:

with the_data(name, people, indicator) as (
values
    ('group 1', 1000, 1),
    ('group 2', 100, 2),
    ('group 3', 2000, 3)
)
select name, people, indicator
from (
    select *, sum(people) over (order by name)
    from the_data
    cross join (select sum(people)/2 median from the_data) s
    ) s
where sum > median
order by name
limit 1;

  name   | people | indicator 
---------+--------+-----------
 group 3 |   2000 |         3
(1 row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM