使用GROUPBY在mysql中获取所需的行

时间:2016-03-04 14:41:46

标签: mysql group-by

我有一张名为travel的表格如下:

+-------+-----+----------+
| Name  | Day | Distance |
+-------+-----+----------+
| Ravi  | 1   | 10       |
| Ravi  | 2   | 21       |
| Ravi  | 3   | 23       |
| Hari  | 1   | 12       |
| Hari  | 2   | 32       |
| Kiran | 1   | 12       |
| Kiran | 2   | 32       |
| Kiran | 3   | 21       |
| Kiran | 4   | 43       |
+-------+-----+----------+

将sql中的group用作此表

select name, day, distance, sum(distance) as total_dist 
from travel
group by name;

我得到的结果如下

+-------+-----+----------+------------+
| Name  | Day | Distance | total_dist |
+-------+-----+----------+------------+
| Ravi  | 1   | 10       | 54         |
| Hari  | 1   | 12       | 44         |
| Kiran | 1   | 12       | 108        |
+-------+-----+----------+------------+

默认情况下,mysql为未聚合的列提供顶行。但我更希望获得聚合值的所有行或组中底行的行,如下所示:

+-------+-----+----------+------------+
| Name  | Day | Distance | total_dist |
+-------+-----+----------+------------+
| Ravi  | 3   | 23       | 54         |
| Hari  | 2   | 32       | 44         |
| Kiran | 4   | 43       | 108        |
+-------+-----+----------+------------+

或以这种方式:

+-------+-----+----------+------------+
| Name  | Day | Distance | total_dist |
+-------+-----+----------+------------+
| Ravi  | 1   | 10       | 54         |
| Ravi  | 2   | 21       | 54         |
| Ravi  | 3   | 23       | 54         |
| Hari  | 1   | 12       | 44         |
| Hari  | 2   | 32       | 44         |
| Kiran | 1   | 12       | 108        |
| Kiran | 2   | 32       | 108        |
| Kiran | 3   | 21       | 108        |
| Kiran | 4   | 43       | 108        |
+-------+-----+----------+------------+

我是使用mysql的新手,并且在使用group by时感到困惑,如果以上两个结果中的任何一个都可以获得,请引导我。

2 个答案:

答案 0 :(得分:0)

要为每个组获取包含sum的整个列表,您可以使用子查询并将join总回到原始表:

select t.name, t.day, t.distance, t2.total_dist
from travel t
  join (select name, sum(distance) total_dist
        from travel
        group by name) t2 on t.name = t2.name

或者为了获得每个组的max天,只需在子查询中包含max(day)

select t.name, t.day, t.distance, t2.total_dist
from travel t
  join (select name, sum(distance) total_dist, max(day) max_day
        from travel
        group by name) t2 on t.name = t2.name and t.day = t2.max_day

答案 1 :(得分:0)

它适合你

select name,max(day),max(distance)
from tablename
group by name 

和其他案例

select name,max(day),max(distance),(select sum(distance) from table) as total_dist
from tablename
group by name