Problem solve Get help with specific problems with your technologies, process and projects.

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 last published in May 2004

Dig Deeper on Oracle and SQL



Find more PRO+ content and other member only offers, here.

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.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.