How to find median by attribute with Postgres window functions?

前端 未结 1 518
鱼传尺愫
鱼传尺愫 2021-01-26 13:36

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

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


        
相关标签:
1条回答
  • 2021-01-26 14:03

    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)
    
    0 讨论(0)
提交回复
热议问题