views:

99

answers:

3

I'm having a hard time creating a query for smth that sounds like this: what is the name and color of the items that cost more than grey box detergent(2 attributes: color:grey, type:detergent).

NOTE: I'm NOT allowed to user subqueries or use the price as a constant.

using subqueries I managed to get this:

SELECT name, color
FROM items
WHERE cost > (SELECT price FROM items WHERE type='detergent' AND color='grey');

any ideas on how can I get the above query without using a subquery?

I'm running out of ideas...

+5  A: 

You can use a join to self.

SELECT i1.name, i1.color
FROM items i1
INNER JOIN items i2 
  ON (i2.type = 'detergent' 
     AND i2.color = 'grey' 
     AND i1.cost > i2.cost)
Matti Virkkunen
Don;t know if OPs scenario allows this, but this solution will include results from all higher price grey detergent records if there is more than one grey detergent.
Charles Bretana
well, the questions specifies that we're not supposed to use price as a constant or subqueries. I came over this solution before, but thought that cost shouldn't be used.
bsuv
Actually, what is the difference between cost and price? It seems they got lumped into one in my mind.
Matti Virkkunen
oh, yeah. they are the same(my view of the query was initially with price)
bsuv
A: 

This way:

SELECT distinct others.name, others.color
FROM items others
   Join items GreyDet
       On others.Price > greyDet.Price
WHERE others.type <> 'detergent'
    And others.Color <> 'grey'
    And greyDet.type = 'detergent'
    And greyDet.Color = 'grey';

NOTE: This solution restricts output to only rows that are not grey detergents. This is necessary if it is possible to have more than one grey detergent record, with different prices..

Charles Bretana
A: 

SELECT name, color FROM items t1 join (SELECT price FROM items WHERE type='detergent' AND color='grey') t2 on t1.price > t2.price;

Bob