ORACLE:在第1列中选择de MAX值之后,在第2列中选择de MAX值

时间:2019-01-24 17:20:28

标签: sql oracle

我在ORACLE中有一个表T,值:

cod1 cod2  A   B
==================
A    AA    2   0
A    AB    2   2
B    BB    1   2
A    AA    3   0
A    AA    3   1
B    BB    2   1    

我想返回具有MAX(A)的MAX(B)的记录(cod1 cod2)。 例如:

A    AA    3   1
A    AB    2   2
B    BB    2   1

这可能吗?

select cod1, cod2, MAX(B) 
from T
group by cod1, cod2
where (cod1, cod2, A) IN (
   select cod1, cod2, MAX(A) 
   from T
   group by cod1, cod2
);

3 个答案:

答案 0 :(得分:2)

为什么不做简单的聚合:

select cod1, cod2, max(a), max(b)
from t
group by cod1, cod2;

如果您想要完整的记录,则可以使用 correlated 子查询:

select t.*
from t 
where t.b = (select t1.b
             from t t1 
             where t1.cod1 = t.cod1 and t1.cod2 = t.cod2
             order by t1.a desc, t1.b desc
             fetch first 1 rows only
            );

答案 1 :(得分:1)

我们可以在此处尝试使用ROW_NUMBER进行两级排序:

WITH cte AS (
    SELECT cod1, cod2, A, B,
        ROW_NUMBER() OVER (PARTITION BY cod1, cod2 ORDER BY A DESC, B DESC) rn
    FROM yourTable
)

SELECT cod1, cod2, A, B
FROM cte
WHERE rn = 1;

enter image description here

Demo

答案 2 :(得分:0)

(继续解决第一个问题)

如果我想返回带有“ 1”或“ 0”的其他“ MAXs”列的表?

示例:

cod1 cod2  A   B   MAXs
=======================
 A    AA   2   0    0
 A    AB   2   2    1
 B    BB   1   2    0
 A    AA   3   0    0
 A    AA   3   1    1
 B    BB   2   1    1