I have a list of Products
upc | name | price | qty
----------------------------
1 | apple | 1.00 | 3
2 | peach | 2.00 | 7
3 | melon | 1.75 | 2
and SaleProducts
upc | price
------------
2 | 1.90
I want to select from Products but also sale price from SaleProducts (if product is on sale). This is what I came up with:
SELECT t1.upc, t1.name, MIN(t1.price) AS 'price', t1.qty
FROM (
SELECT p.upc, p.name, p.price, p.qty
FROM products p
UNION
SELECT sp.upc, NULL, sp.price, NULL
FROM saleproducts sp
) t1
GROUP BY t1.upc;
Output:
upc | name | price | qty
----------------------------
1 | apple | 1.00 | 3
2 | peach | 1.90 | 7
3 | melon | 1.75 | 2
Can anyone suggest a more elegant way to accomplish this? Im aware of similar question but my goal is to grab whichever price is lower, so COALESCE
wouldn't work.
The only restriction is, I must use vanilla SQL, no stored procs or IF's.
Try this instead using CASE
:
SELECT p.upc, p.name,
CASE WHEN sp.price IS NOT NULL
THEN CASE WHEN p.price > sp.price
THEN sp.price
ELSE p.price
END
ELSE p.price
END price, p.qty
FROM products p LEFT JOIN saleproducts sp ON p.upc = sp.upc;
It will prefer to use the price from saleproducts
when it's available. If there is not a sale price for that product it will instead use the price from products
.
EDIT - I've updated my answer so that it always gets the lowest price. FWIW I can't imagine why you'd bother having a sale price which is actually higher than your list price.
This seems more like the job for a left outer join
:
SELECT p.upc, p.name,
(case when sp.price is null or p.price < sp.upc then p.price
else sp.price
end) as price,
p.qty
FROM products p left outer join
salesproducts sp
on p.upc = sp.upc;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.