Ask the Expert

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 columns.

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?


    Requires Free Membership to View

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
group
    by Name

Sweet, eh?

For More Information


This was first published in May 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
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
Sort by: OldestNewest

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: