0

我的问题与 Select 有关,我想按 ASC 和 DESC 排序字段,请看示例:

我有表格产品,我要订购的字段称为价格,所以,我知道我可以这样做:

SELECT Price FROM Products ORDER BY Price ASC.

但我想看看最高价格和最低价格,因为我知道我能做到的最高价格:

 SELECT Price FROM Products ORDER BY Price ASC limit 1; 

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

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

问候。

4

5 回答 5

4

MIN简单和MAX聚合函数的使用怎么样

SELECT MAX(Price) as MaxPrice, MIN(Price) as MinPrice FROM Products
于 2013-04-13T20:52:21.300 回答
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)
于 2013-04-13T21:21:44.133 回答
0

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

于 2013-04-13T20:49:35.100 回答
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
于 2013-04-13T20:51:45.440 回答
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)
于 2013-04-13T20:58:07.467 回答