How to find median by attribute with Postgres window functions?

非 Y 不嫁゛ 提交于 2019-12-20 07:27:14

问题


I use PostgreSQL and have records like this on groups of people:

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. 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.

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.


回答1:


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)


来源:https://stackoverflow.com/questions/40928877/how-to-find-median-by-attribute-with-postgres-window-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!