|
我有一张桌子id,year和count。
. b9 L) ]+ x5 O% Q我想MAX(count)为每个获取id并保留year发生时间如下:# E, e8 c3 N$ T) G
SELECT id,year,MAX(count)FROM tableGROUP BY id;不幸的是,这给了我一个错误:
0 C5 f7 p# w8 x3 h: K) d- B错误:“ table.year必须出现列GROUP BY子句中或在聚合函数中使用2 W# b, h, b* F/ ~
所以我试了:
. Z; p6 g) U8 C; v4 v: r3 T* v5 wSELECT id,year,MAX(count)FROM tableGROUP BY id,year;然后,它不执行任何操作MAX(count),只按原样显示表。我猜是因为按year和分组时id,它将获得该id特定年份的最大值。, f% n1 E0 v4 E: T- W
那么,如何编写查询呢?我想得到它id麓小号MAX(count)这种情况发生在当年。4 Q" C* y4 I$ L/ J
# e+ o. @& N/ V3 b# t! ~
解决方案:
3 J8 w1 U, k7 m' Y$ _+ |6 l select *from ( select id, year, thing, max(thing) over (partition by id) as max_thing from the_table) twhere thing = max_thing或者:
$ Q3 ]' x5 G. d$ O; s; G# cselect t1.id, t1.year, t1.thingfrom the_table t1where t1.thing = (select max(t2.thing) from the_table t2 where t2.id = t1.id);或者
, z! |' y# T3 z' b% oselect 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或者(与前者相同,但符号不同)4 T4 C/ t: T, y* R
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 |
|