Reputation: 53
I'm trying to get the lowest price of a specific quote on SQL. I tried the following with erroneous results:
SELECT * FROM price WHERE price=(SELECT MIN(price) as price FROM price WHERE id_quote=36
SELECT id_provider, MIN(price) as price FROM price WHERE id_quote=36
I understand that I'm getting multiple results on the first query if I have the same price in that table regardless of the quote. But I don't know why the second isn't giving me the correct results.
I need to call only id_provider and its price from that specific quote (no group).
Any help?
Upvotes: 0
Views: 2871
Reputation: 4345
I like using RANK() for this kind of problem:
SELECT id_quote, id_provider, price
FROM
(
SELECT id_quote id_provider, price,
RANK() OVER(PARTITION BY id_quote ORDER BY price ASC) AS rnk
FROM price
) sub
WHERE rnk = 1
Upvotes: 1
Reputation: 1030
You can do it this way if you want:
SELECT TOP 1 id_provider, price FROM price WHERE id_quote=36 ORDER BY price ASC
Upvotes: 0
Reputation: 1269853
I think you just need a correlated subquery:
SELECT p.*
FROM price p
WHERE p.id_quote = 36 AND
p.price = (SELECT MIN(p2.price) FROM price p2 WHERE p2.id_quote = p.id_quote);
Notice that the "quote" condition has moved to the outer query.
Upvotes: 2