Mysql在几个范围内获得最大值

时间:2015-06-17 10:05:34

标签: mysql

这个问题与mysql有关。我想获得几组最小值和最大值的最大值。没有定义组列,"组"基于我定义的范围。我认为通过一个例子可以更好地解释这一点。我想要的是以下一组查询到一个查询:

select max(value) from tablename where value between 5000 and 5499;
select max(value) from tablename where value between 7500 and 7999;
select max(value) from tablename where value between 7000 and 7499;
select max(value) from tablename where value between 6500 and 6999;
select max(value) from tablename where value between 6000 and 6499;
select max(value) from tablename where value between 5500 and 5999;
select max(value) from tablename where value between 8001 and 8998;

所以我可以得到每个范围的最大值列表。在任何问题上我都没有发现任何相似之处。

非常感谢

3 个答案:

答案 0 :(得分:3)

尝试:

  SELECT MAX(value)
    FROM tablename
   WHERE value BETWEEN 5000 AND 8998
GROUP BY FLOOR(value / 500)

SQL Fiddle

答案 1 :(得分:1)

我要做的是使用这样的查询:

SELECT
  range1, range2, max(value)
FROM
  (SELECT 5000 AS range1, 5499 AS range2
   UNION ALL SELECT 7500, 7999
   UNION ALL SELECT 7000, 7499
   UNION ALL SELECT 6500, 6999
   UNION ALL SELECT 6000, 6499
   UNION ALL SELECT 5500, 5999
   UNION ALL SELECT 8001, 8998
  ) AS ranges
  LEFT JOIN tablename ON value BETWEEN range1 AND range2
GROUP BY
  range1, range2

当然,如果范围与您给出的范围相似,则可以使用公式计算范围,但在此您可以自由定义任何您想要的范围。您可能还希望使用具有适当索引的“范围”表来获得更好的性能。

答案 2 :(得分:0)

select max(case when value between 5000 and 5499 then value else 0 end) as max_5000_5499,
       max(case when value between 7500 and 7999 then value else 0 end) as max_7500_7999
from tablename