回答

收藏

PostgreSQL MAX和GROUP BY

技术问答 技术问答 579 人阅读 | 0 人回复 | 2023-09-14

我有一张桌子id,year和count。
9 j& K* e9 r7 b; Z* K1 J! i我想MAX(count)为每个获取id并保留year发生时间如下:3 w3 h+ P6 G# _+ [: W% _/ K
SELECT id,year,MAX(count)FROM tableGROUP BY id;不幸的是,这给了我一个错误:0 s8 v1 F9 x0 S1 ^
错误:“ table.year必须出现列GROUP BY子句中或在聚合函数中使用
6 J% {( g6 `' W  b& r+ o! o' a: I
所以我试了:
, E1 d2 Q9 u% Q9 {  a1 ^8 q) BSELECT id,year,MAX(count)FROM tableGROUP BY id,year;然后,它不执行任何操作MAX(count),只按原样显示表。我猜是因为按year和分组时id,它将获得该id特定年份的最大值。
& G) A: \% {8 s% C, w# W1 x3 Y) x那么,如何编写查询呢?我想得到它id麓小号MAX(count)这种情况发生在当年。
' O$ J9 N1 M  e. {* _' H                                                               
/ G7 p! i) Z6 ~, O$ T    解决方案:                                                               
3 F3 V: w! a! O" n, a0 s                                                                select *from (  select id,         year,        thing,        max(thing) over (partition by id) as max_thing  from the_table) twhere thing = max_thing或者:
! ^" f8 @6 g# L: W$ P/ H8 xselect t1.id,      t1.year,      t1.thingfrom the_table t1where t1.thing = (select max(t2.thing)                   from the_table t2                                                                                                                                                                                                                                                                                        where t2.id = t1.id);或者6 Z4 l' j8 n) ?1 ~8 n
select t1.id,      t1.year,      t1.thingfrom 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或者(与前者相同,但符号不同)6 }6 g3 x; h- A0 Q
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.thingfrom the_table t1  join max_stuff t2     on t1.id = t2.id    and t1.thing = t2.max_thing
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则