简体   繁体   中英

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:

  • 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?

价格表

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.

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
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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM