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

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

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

Dig Deeper on Oracle and SQL

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.