0

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.

2 Answers 2

1

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;
1
  • If primary_key_id is a FK and 123 needs to be dynamic, we need to alias the inner query and have it in the SELECT clause. Nonetheless, I had simplified my question to get an insight into the core solution. Thank you for your help.
    – Malvon
    Mar 21, 2014 at 20:14
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.