Standage
Standage

Reputation: 1517

Group by two columns and by max of another column

I need to be able to group by two columns and only bring back the row where the id of another column for these two columns is the max value. The details I'm after are in the fourth column say called answer

COLUMN1 | COLUMN2 | NUMBERCOL  |  Answer
--------------- ----------------------------
 123    |   456   |      1     |    a
 123    |   456   |      2     |    x
 123    |   456   |      3     |    s
 654    |   564   |      1     |    a
 654    |   564   |      2     |    s
 654    |   564   |      3     |    p
 654    |   564   |      4     |    b

So I need answer s from the first grouping results and answer b from the second grouping results

Upvotes: 2

Views: 259

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269533

You can use analytic functions for this:

select t.*
from (select t.*,
             row_number() over (partition by column1, column2 order by numbercol desc) as seqnum
      from t
     ) t
where seqnum = 1

This works not by aggregating the data, but by assigning a sequential number to the rows. The sequential number starts over again for each new value of (column1, column2) and the ordering is determined by numbercol. The highest numbercol gets a value of 1, the second highest 2, and so on. This is an example of an analytic function in Oracle (called "window" function in other databases).

The final where clause chooses the row that you want -- the one with the highest numbercol.

Upvotes: 2

Taryn
Taryn

Reputation: 247650

You can use a subquery with a JOIN to get the result:

select t1.column1,
  t1.column2,
  t1.numbercol,
  t1.answer
from yourtable t1
inner join
(
  select column1, column2,
    max(numbercol) MaxNum
  from yourtable
  group by column1, column2
) t2
  on t1.column1 = t2.column1
  and t1.column2 = t2.column2
  and t1.numbercol = t2.MaxNum

See SQL Fiddle with Demo

Upvotes: 3

Related Questions