Highest value in each row

In the database example below, I would like the HiGame column to display the highest game from each bowler's game


Name  Game1  Game2   Game3   HiGame 
Rick  200    210     195     (210)
Frank 195    186     145     (195)

I've tried to find a way to use the MAX function, but nothing works. Is what I want possible?

Yes, what you want is possible, but it's ugly. And it doesn't scale.

MAX is not right for your table. MAX is an aggregate, used to find the highest value in a column of data. You have to find the highest row value yourself.

select Name
     , Game1
     , Game2
     , Game3
     , case when Game1 >= Game2
             and Game1 >= Game3
            then Game1
            when Game2 >= Game1
             and Game2 >= Game3
            else Game3
        end as HiGame
  from yourtable

See what happens when you add a 4th game:

select Name
     , Game1
     , Game2
     , Game3
     , Game4
     , case when Game1 >= Game2
             and Game1 >= Game3
             and Game1 >= Game4
            then Game1
            when Game2 >= Game1
             and Game2 >= Game3
             and Game2 >= Game4
            when Game3 >= Game1
             and Game3 >= Game2
             and Game3 >= Game4
            else Game4
        end as HiGame
  from yourtable

Clearly, a scaling nightmare. However, if you were to store your data like this:

Name  Game
Rick   200    
Rick   210
Rick   195
Frank  195
Frank  186
Frank  145

Then you could run this query no matter how many games each player played.

select Name
     , max(Game) as HiGame
  from yourtable
    by Name

Sweet, eh?

For More Information

This was first published in May 2004

Dig deeper on Oracle and SQL



Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.



Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: