Hello World
Hello World

Reputation: 57

finding maximum values using Oracle / SQL group by

I need to write a query for a table with 5 columns which are ID1, ID2, ID3, A, and B. Here, ID1, ID2, and ID3 form the primary key.

For each ID1, find maximum A. If two or more As have the maximum values, choose the only one record that has maximum B. Finally show the results with corresponding ID2 and ID3 values.

For example, for the following table

ID1 ID2 ID3   A  B
  1   2   3  10  5 
  1   3   4  30  4
  1   3   5  30  3
  2   2   3   5  1
  2   3   4   9  2
  2   3   5  11  3

the query should show the results as follows.

ID1 ID2 ID3  Max_A  
  1   3   4     30  
  2   3   5     11  

Upvotes: 2

Views: 172

Answers (1)

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58431

The gist of this is to

  • add a ROW_NUMBER to each row
  • restart the number for each ID1
  • ORDER from high to low on A and B.
  • put it in a CTE for easy access on rn

SQL Statement

;WITH q AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY ID1 ORDER BY A DESC, B DESC) AS rn
  FROM YourTable
)
SELECT *
FROM   q
WHERE  rn = 1

Upvotes: 3

Related Questions