按最高和最低排序

时间:2013-04-13 20:48:27

标签: mysql sql select sql-order-by

我的问题与Select有关,我想通过ASC和DESC订购一个字段,看看例子:

我有产品表,我想订购的字段叫做Price,所以,我知道我可以这样做:

SELECT Price FROM Products ORDER BY Price ASC.

但我希望看到最高价格和最低价格,我知道我能做到的最高价格:

 SELECT Price FROM Products ORDER BY Price ASC limit 1; 

那么,如何在1选择中选择最高值和最低值?

我还想选择价值最高的产品名称和最低价格的产品。

问候。

5 个答案:

答案 0 :(得分:4)

如何使用简单的MINMAX聚合函数

SELECT MAX(Price) as MaxPrice, MIN(Price) as MinPrice FROM Products

答案 1 :(得分:2)

这将显示所有具有最高价格或最低价格的产品:

SELECT Products.*
FROM Products
WHERE Price = (SELECT MAX(Price) FROM Products)
      OR Price = (SELECT MIN(Price) FROM Products)

或许你想要这样的东西:

SELECT
  Products.*,
  m.mx As Highest,
  m.mn As Lowest,
  CASE WHEN Products.Price = m.mx THEN 'Max' ELSE 'Min' END As Is_Max_or_Min
FROM
  Products INNER JOIN (
    SELECT MAX(Price) mx, MIN(Price) mn
    FROM Products
  ) m ON Products.Price IN (m.mx, m.mn)

如果您希望它们位于同一行,并且只有一种产品具有最高价格且只有一种具有最小价格,则可以使用以下内容:

SELECT
  m.Lowest, p1.Name Name_Lowest,
  m.Highest, p2.Name Name_Highest
FROM
  (SELECT MIN(Price) Lowest, MAX(Price) Highest FROM Products) m
  INNER JOIN Products p1 ON m.Lowest = p1.Price
  INNER JOIN Products p2 ON m.Highest = p2.Price
LIMIT 1

或者,如果你只需要一些更简单的东西,你可以使用它:

(SELECT 'Max' Is_Max_Or_Min, Products.*
 FROM Products ORDER BY Price DESC LIMIT 1)
UNION ALL
(SELECT 'Min', Products.*
 FROM Products ORDER BY Price LIMIT 1)

答案 2 :(得分:0)

SELECT Price FROM Products ORDER BY Price DESC limit 1; ??

答案 3 :(得分:0)

如果您想查看最高价和最低价,请使用此查询:

select highest, lowest from
(
SELECT Price as highest FROM Products ORDER BY Price DESC limit 1;
SELECT Price as lowest FROM Products ORDER BY Price ASC limit 1;
) t

答案 4 :(得分:0)

最简单的方法是:

SELECT MIN(Price) LowestPrice, MAX(Price) HighestPrice FROM Products

但在某些情况下,您可能希望使用UNION声明:

(SELECT 'Lowest'  type, Price FROM Products ORDER BY Price ASC  LIMIT 1)
UNION
(SELECT 'Highest' type, Price FROM Products ORDER BY Price DESC LIMIT 1)