Reputation: 45
I got rows like these in a table:
PRODUCTID | NAME | LOCATION | PRICE
1 X R 5
1 X C 4.5
2 Y R 5
3 Z C 4.5
As you can see, the table can contain the same product but in different locations. All of the products are in the 'R' location, but sometimes a product can be in both the R and C Location with different prices.
What I want is that if a product is in both locations R and C, only get the location C, but if it's only in the R location, then just get the R one.
How can I accomplish This?
I have tried using sub queries:
SELECT *
FROM ProductLocation t
WHERE EXISTS (
SELECT *
FROM ProductLocation
WHERE
LOCATION not in ('R')
)
and t.PRODUCTID='1'
Upvotes: 2
Views: 540
Reputation: 12169
I think this may work also:
select * from
(select p.*, row_number() over
( partition by productid, name
order by case when location = 'C' then 1 else 2 end) rnum
from productlocation p)
where rnum = 1
Upvotes: 2
Reputation: 1269953
Probably the most efficient way is:
select pl.*
from ProductLocation pl
where pl.location = 'C'
union all
select pl.*
from ProductLocation pl
where pl.location = 'R' and
not exists (select 1
from ProductLocation pl2
where pl2.productId = pl.productId and
pl2.location = 'C'
);
For performance, you want indexes on ProductLocation(location)
and ProductLocation(productId, location)
.
Upvotes: 2