sql - Selecting rows with maximum value in Oracle query
问题描述
Let's say I've got this rows in my Oracle database:
N783AS 6 WA
N794SW 2 WA
N407SW 2 WI
N471CA 10 WI
N479CA 6 WI
N494CA 5 WI
N495CA 7 WI
N496CA 12 WI
N498CA 9 WI
N506CA 8 WI
N507CA 6 WI
What I'd like to obtain is this:
N496CA 12 WI
N783AS 6 WA
So, what I should do is, somehow, obtain, for each state (third column), the row with the maximum value of the second column. How can I do so?
解决方案
最简单的方法是where
子句中的相关子查询:
select t.*
from t
where t.col2 = (select max(t2.col2) from t t2 where t2.col3 = t.col3);
使用索引(col3, col2)
可能是性能最高的解决方案,但它可以返回重复项。为避免这种情况,您可以使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by col3 order by col2 desc) as seqnum
from t
) t
where seqnum = 1;
或者,这在某些情况下可能具有更好的性能:
select max(col1) keep (dense_rank first order by col2 desc), max(col2), col3
from t
group by col3;
推荐阅读
- swift - SKProduct Swift - 信息从何而来?
- javascript - Puppeteer:在 page.$eval 内执行 element.click()
- postgresql - 如何监控来自从站的异步流复制延迟?
- reactjs - ReachRouter 在组件构造函数中导航
- sap - 在 sap hybris 中,是否有任何内置方式可以在产品图像上显示标签?
- html - CSS 检查元素是否存在并应用于第一个元素
- c++ - try_emplace 的惰性参数评估?
- android - 使用 Kotlin 从 Uri 创建文件
- c# - 由于 Startup.Configure NullReferenceException,新生成的 ASP.NET Core 3.1 应用程序将无法运行
- php - 如何在 laravel 查询中添加整理