SQL: getting the max value of one column and the corresponding other columns [duplicate]

有些话、适合烂在心里 提交于 2021-02-02 03:42:27

问题


ID|  tag  |  version
-----+-----+-----
1|  A  |  10
2|  A  |  20
3|  B  |  99
3|  C  |  30
3|  F  |  40

desired output:

1 A 10
2 A 20
3 B 99

How can I get the max version of every ID and the corresponding tag for that version? Speed is important (I have around 28m rows) so a nested Select won't do it. Also a simple Group by ID with a max(version) doesn't work because I also need the corresponding Tag where the version is max.


回答1:


Use ROW_NUMBER() :

SELECT s.id,s.tag,s.version FROM (
    SELECT t.*,
           ROW_NUMBER() OVER(PARTITION BY t.id ORDER BY t.version DESC) as rnk
   FROM YourTable t) s
WHERE s.rnk = 1



回答2:


Try this

select id, max(tag) keep(dense_rank first order by VERSION desc) as tag, max(version) as version
from t group by id


来源:https://stackoverflow.com/questions/38304630/sql-getting-the-max-value-of-one-column-and-the-corresponding-other-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!