Pergunta

I am working on an Oracle 11g database query that needs to retrieve a list of the highest NUM value between duplicated rows in a table.

Here is an example of my context:

ID  |  NUM
------------
1   |  1111 
1   |  2222 
2   |  3333
2   |  4444
3   |  5555
3   |  6666

And here is the result I am expecting after the query is executed:

NUM
----
2222    
4444
6666

I know how to get the GREATEST value in a list of numbers, but I have absolutely no guess on how to group two lines, fetch the biggest column value between them IF they have the same ID.

Programmaticaly it is something quite easy to achieve, but using SQL it tends to be a litle bit less intuitive for me. Any suggestion or advise is welcomed as I don't even know which function could help me doing this in Oracle.

Thank you !

Foi útil?

Solução

This is the typical use case for a GROUP BY. Assuming your Num field can be compared:

SELECT ID, MAX(NUM) as Max
FROM myTable
GROUP BY ID

If you don't want to select the ID (as in the output you provided), you can run

SELECT Max
FROM (
    SELECT ID, MAX(NUM) as Max
    FROM myTable
    GROUP BY ID
) results

And here is the SQL fiddle

Edit : if NUM is, as you mentioned later, VARCHAR2, then you have to cast it to an Int. See this question.

Outras dicas

The most efficient way I would suggest is

SELECT ids, 
       value 
FROM   (SELECT ids, 
               value, 
               max(value) 
                 over ( 
                   PARTITION BY ids) max_value 
        FROM   test) 
WHERE  value = max_value; 

This requires that the query maintain a single value per id of the maximum value encountered so far. If a new maximum is found then the existing value is modified, otherwise the new value is discarded. The total number of elements that have to be held in memory is related to the number of ids, not the number of rows scanned.

See this SQLFIDDLE

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top