简体   繁体   中英

How to find median by attribute with Postgres window functions?

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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