如何从表中选择多个最大值和最小值

时间:2015-10-10 11:09:38

标签: mysql sql

我编写了一个返回一列数字并从最低到最高排序的查询。我需要显示最高和最低值。我打算使用一个简单的SELECT MAX(x),MIN(x)FROM ...但是该表包含多个最小值,并且该语句仅选择第一个最小值。

 Example of table
 Name x
 a    1
 b    1
 c    1
 d    2
 e    5

我将如何显示

 Name x
 a    1
 b    1
 c    1
 e    5

这只是一个例子,最大值和最小值之间有一系列行。

2 个答案:

答案 0 :(得分:3)

一种方法是使用join和聚合:

select e.*
from example e join
     (select min(x) as minx, max(x) as maxx
      from example
     ) em
     on e.x = minx or e.x = maxx;

但是,如果您在x上有索引,那么将其标记为以下内容可能更有效:

select e.*
from example e
where e.x = (select max(x) from example) union all
select e.*
from example e
where e.x = (select min(x) from example) and

每个子查询都将使用索引。第二个假设min(x)max(x)不同。这可以使用union轻松修复,但这会增加开销。代替:

select e.*
from example e
where e.x = (select max(x) from example) union all
select e.*
from example e
where e.x = (select min(x) from example) and
      (select min(x) from example) <> (select max(x) from example);

这应该继续有效地使用索引。我认为以下内容也可行:

where e.x = (select min(x) from example having min(x) <> max(x))

答案 1 :(得分:1)

您可以使用返回MINMAX的子查询加入。 UNION会删除重复项MAX = MIN

<强> SqlFiddleDemo

CREATE TABLE tab(Name NVARCHAR(100), x INT);

INSERT INTO tab
VALUES ('a',    1), ('b',    1), ('c',    1), ('d',    2), ('e',    5);

SELECT t.*
FROM tab t 
JOIN (SELECT MIN(x) AS val 
      FROM tab
      UNION
      SELECT MAX(x) AS val
      FROM tab) AS sub
 ON t.x = sub.val;