PostgreSQL MAX and GROUP BY

后端 未结 2 677
一整个雨季
一整个雨季 2021-01-30 06:20

I have a table with id, year and count.

I want to get the MAX(count) for each id and keep the yea

2条回答
  •  萌比男神i
    2021-01-30 07:08

    select *
    from (
      select id, 
             year,
             thing,
             max(thing) over (partition by id) as max_thing
      from the_table
    ) t
    where thing = max_thing
    

    or:

    select t1.id,
           t1.year,
           t1.thing
    from the_table t1
    where t1.thing = (select max(t2.thing) 
                      from the_table t2
                      where t2.id = t1.id);
    

    or

    select t1.id,
           t1.year,
           t1.thing
    from the_table t1
      join ( 
        select id, max(t2.thing) as max_thing
        from the_table t2
        group by id
      ) t on t.id = t1.id and t.max_thing = t1.thing
    

    or (same as the previous with a different notation)

    with max_stuff as (
      select id, max(t2.thing) as max_thing
      from the_table t2
      group by id
    ) 
    select t1.id, 
           t1.year,
           t1.thing
    from the_table t1
      join max_stuff t2 
        on t1.id = t2.id 
       and t1.thing = t2.max_thing
    

提交回复
热议问题