Philippe Winter
Philippe Winter

Reputation: 53

SQL SELECT MIN value with WHERE statement

I'm trying to get the lowest price of a specific quote on SQL. I tried the following with erroneous results:

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?

Table price

Upvotes: 0

Views: 2871

Answers (3)

kjmerf
kjmerf

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

slon
slon

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

Gordon Linoff
Gordon Linoff

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

Related Questions