Ask the Expert

The effect of normalization on query simplicity

How would I select the column that contains the highest value for each row?

ID  Store   Shoes   Shirts  Pants
01    A       1        2       3
02    B       3        1       2
03    C       2        3       1

I want to return something like:

A  Pants
B  Shoes
C  Shirts

    Requires Free Membership to View

To get exactly what you asked for:

select Store
     , case when Shoes >= Shirts 
             and Shoes >= Pants
            then 'Shoes'
            when Shirts >= Shoes
             and Shirts >= Pants
            then 'Shirts'
            when Pants >= Shoes
             and Pants >= Shirts
            then 'Pants'
            else null
  from Stores

Ugly, and even uglier if you ever have to handle additional columns. Feel free to imagine what the query would look like if there were a realistic number of columns, like 187.

What you should do is have two tables instead of one:


ID  Store
01    A  
02    B  
03    C  

ID   Item    Qty
01  'Shoes'   1
01  'Shirts'  2
01  'Pants'   3
02  'Shoes'   3
02  'Shirts'  1
02  'Pants'   2
03  'Shoes'   2
03  'Shirts'  3
03  'Pants'   1

Now you can handle as many items as you wish with this query:

select Store
     , Item
  from Stores S
  join Inventory I
    on S.ID = I.ID
 where Qty = 
       ( select max(Qty)
           from Inventory
          where ID = I.ID )

For More Information

This was first published in April 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: