Question

In Oracle DB, I need to make a query to grab a MAX() of certain column while also have another field in the SELECT statement. i.e.

PRIMARY_KEY_ID | FIELD_A | FIELD_B
---------------------------------------
123            | AFB     | 01-JAN-2002
123            | AFB     | 02-FEB-2002
123            | AFB     | 03-MAY-2002
123            | COB     | 15-JAN-2003
123            | COB     | 18-DEC-2004

Running the following query would result in:

SELECT
  field_a,
  MAX(field_b)
FROM table_a
GROUP BY primary_key_id, field_a
HAVING primary_key_id = 123;


FIELD_A | FIELD_B
----------------------
AFB     | 03-MAY-2002
COB     | 18-DEC-2004

My intention is to only return a single row: the latest date for FIELD_B, in this case 18-DEC-2004. However, due to the fact that a pair of (*PRIMARY_KEY_ID*, *FIELD_A*) is going to return two rows (since PRIMARY_KEY_ID is unique but FIELD_A is not), the result set would not return a desired row.

Was it helpful?

Solution

You need to find the max within the group of primary_key_id and then filter out the result with field_b that is equal to max value within the group. Hope it helps

select field_a, field_b
  from (select field_a,
               field_b,
               max(field_b) over (partition by primary_key_id) as max_b
          from table_a)
 where primary_key_id=123
   and field_b = max_b;

OTHER TIPS

You can try using the below query

         SELECT
         field_a,
         MAX(field_b) over (partition by primary_key_id) 
         FROM table_a
         where primary_key_id=123;

Hope it Helps

Vishad

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top