小编典典

PostgreSQL MAX和GROUP BY

sql

我有一张桌子idyearcount

我想MAX(count)为每个获取id并保留year它发生的时间,因此我进行了以下查询:

SELECT id, year, MAX(count)
FROM table
GROUP BY id;

不幸的是,这给了我一个错误:

错误:“ table.year”列必须出现在GROUP BY子句中或在聚合函数中使用

所以我尝试:

SELECT id, year, MAX(count)
FROM table
GROUP BY id, year;

但是然后,它不执行任何操作MAX(count),仅按原样显示该表。我猜想是因为按year和分组时id,它将获得该id特定年份的最大值。

那么,如何编写该查询?我想获得id麓小号MAX(count)和当年当这种情况发生。


阅读 265

收藏
2021-04-15

共1个答案

小编典典

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

或者:

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);

或者

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

或(与前一个相同,但符号不同)

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
2021-04-15