Search code examples
oracle-databasemaxanalytic-functionspartition-by

Find the maximum value in a column for each partition


I have 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
);

It has 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 value of col4 which has maximum value for combination of col2 and col3. e.g. my result should be:

col4
  Z
  M

I tried to use oracle analytic function:

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

But it is not working as expected. Can you please help me to resolve this issue?

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 any better way than this?


Solution

  • If you expect that result:

    col4
      Z
      M
    

    You should write:

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

    This will return the maximum value found in column col4 for each pair of col2,col3


    If you need that:

    COL2    COL3    COL4
    A       B       Z
    C       D       M
    

    Write:

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

    Finally, if you need:

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

    There are many variations. Like this one:

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