微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL MAX和GROUP BY




我有一个id,年和数的表.

我想得到每个id的MAX(count),并保持发生的一年,所以我做这个查询

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

不幸的是,它给我一个错误

ERROR: column “table.year” must appear in the GROUP BY clause or be
used in an aggregate function

所以我试试:

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

但是,它不做MAX(计数),它只是显示表.我想,因为当按年份和身份分组时,它会获得该特定年份的最大值.

那么,怎么写这个查询呢?我想得到ID的MAX(计数)和发生的那一年.

select *
from (
  select id,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.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.thing
from the_table t1
  join max_stuff t2 
    on t1.id = t2.id 
   and t1.thing = t2.max_thing

原文地址:https://www.jb51.cc/postgresql/192718.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐