Find the maximum value in the column for each section

I have a table structure like:

CREATE TABLE new_test
( col1 NUMBER(2) NOT NULL,
  col2 VARCHAR2(50) NOT NULL,
  col3 VARCHAR2(50) NOT NULL,
  col4 VARCHAR2(50) NOT NULL
);

There is data:

col1    col2    col3    col4
0         A      B       X
1         A      B       Y
2         A      B       Z
1         C      D       L
3         C      D       M

I need to find the col4 value that has the maximum value for the combination of col2 and col3. for example my result should be:

col4
  Z
  M

I tried using oracle analytic function:

SELECT col4, MAX(col1) OVER (PARTITION BY col2, col3) FROM (
SELECT col2, col3, col4, col1 
FROM new_test);

But it does not work as expected. Could you help me solve this problem?

Update: I could make it work using:

SELECT a.col4
FROM new_test a,
  (SELECT col2,
    col3,
    col4,
    MAX(col1) OVER (PARTITION BY col2, col3) AS col1
  FROM new_test
  ) b
WHERE a.col2 = b.col2
AND a.col3   = b.col3
AND a.col4   = b.col4
AND a.col1   = b.col1;

Is there a better way than this?

+4
source share
1 answer

If you expect this result:

col4
  Z
  M

You must write:

SELECT MAX(col4) AS col4 FROM new_test GROUP BY col2,col3

This will return the maximum value found in the column col4for each paircol2,col3


If you need it:

COL2    COL3    COL4
A       B       Z
C       D       M

Record:

SELECT col2,col3,MAX(col4) AS col4 FROM new_test GROUP BY col2,col3

, :

COL1    COL2    COL3    COL4
2       A       B       Z
3       C       D       M

. :

SELECT col1,col2,col3,col4 
  FROM new_test
  NATURAL JOIN (SELECT col2,col3,MAX(col4) AS col4 
                  FROM new_test GROUP BY col2,col3)
+5

All Articles