如何在Mysql中按数值分组

时间:2014-07-23 05:32:39

标签: mysql sql

我有一张名为test的表。它的数据如下。我需要从测试表中获取每个分组的最高数值。

mysql> SELECT * FROM test;
+----+-------+------+
| id | value   | name  |
+----+-------+------+
|  1  |    1   | row1  |
|  2  |    1.2 | row2  |
|  3  |    1.5 | row3  |
|  4  |    2   | row4  |
|  5  |    3   | row5  |
|  6  |    3.1 | row6  |
|  7  |    3.6 | row7  |
|  8  |    4   | row8  |
|  9  |    5   | row9  |
|  10 |    5.1 | row10 |
+----+-------+------+
10 rows in set (0.00 sec)

但我需要结果如下所示,以获得每个数字组的最大值:

+----+-------+------+
| id | value   | name  |
+----+-------+------+
|  1  |    1.5 | row1  |
|  4  |    2   | row4  |
|  7  |    3.6 | row7  |
|  8  |    4   | row8  |
|  10 |    5.1 | row10 |
+----+-------+------+
5 rows in set (0.00 sec)

任何人都可以帮助我?查询将如何?

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望按value列的整数部分对数据进行分组。如果这是正确的,可以这样做:

select max(t.id) as id, max(t.value) as value
from test as t
group by floor(t.value)

如果您想获得匹配的名称,可以将此结果与原始表格结合使用:

select a.*, t.name
from 
    (
        select max(t.id) as id, max(t.value) as value
        from test as t
        group by floor(t.value)
    ) as a
    inner join test as t on a.id = t.id

顺便说一句,在描述您的问题时请更具体

答案 1 :(得分:2)

查询:

SQLFIDDLEEXample

select t1.id,
       t1.value,
       t1.name
from Table1 t1
left join Table1 t2
  ON floor(t2.value) = floor(t1.value)
  AND t2.value > t1.value
WHERE t2.value is null

结果:

| ID | VALUE |  NAME |
|----|-------|-------|
|  3 |   1.5 |  row3 |
|  4 |     2 |  row4 |
|  7 |   3.6 |  row7 |
|  8 |     4 |  row8 |
| 10 |   5.1 | row10 |

答案 2 :(得分:1)

如果您有不同行的唯一值,则可以使用此查询:

SELECT * FROM test WHERE VALUE IN(
    SELECT MAX(value) FROM test GROUP BY FLOOR(value)
)