我们说我在Oracle数据库中有这些行:
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
我想要获得的是:
N496CA 12 WI
N783AS 6 WA
所以,我应该做的是,以某种方式,为每个州(第三列)获得具有第二列最大值的行。我怎么能这样做?
答案 0 :(得分:2)
最简单的方法是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;