Q

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
        end    
  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:

Stores

ID  Store
01    A  
02    B  
03    C  

  
Inventory
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
inner
  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

Dig deeper on Oracle and SQL

Pro+

Features

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.

0 comments

Oldest 

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:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close