SQL: getting the max value of one column and the corresponding other columns(SQL:获取一列和相应其他列的最大值)
问题描述
ID| tag | version
-----+-----+-----
1| A | 10
2| A | 20
3| B | 99
3| C | 30
3| F | 40
期望的输出:
1 A 10
2 A 20
3 B 99
如何获取每个 ID 的最大版本以及该版本的相应标签?速度很重要(我有大约 28m 行),所以嵌套的 Select 不会这样做.此外,一个带有 max(version) 的简单 Group by ID 也不起作用,因为我还需要版本为 max 的相应标签.
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.
推荐答案
使用 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
这篇关于SQL:获取一列和相应其他列的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL:获取一列和相应其他列的最大值


基础教程推荐
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01