SQL从数据库中选择具有最大值的行,并按2列分组

时间:2018-08-28 11:16:29

标签: mysql sql database max left-join

我有这张桌子:

TABLE优惠

 +------+--------------+----------+----------------+
 | id   | player_id    | team_id  | valore         |
 +------+--------------+----------+----------------+
 | 1    | 1            | 1        | 230            |
 | 2    | 1            | 3        | 150            |
 | 3    | 9            | 3        | 150            |
 | 4    | 1            | 5        | 100            |
 | 5    | 7            | 5        | 37             |
 | 6    | 7            | 1        | 38             |
 +------+--------------+----------+----------------+

我希望这个结果, 我想创建一个这样的视图:

+------+--------------+----------+----------------+
| id   | player_id    | team_id  | valore         |
+------+--------------+----------+----------------+
| 1    | 1            | 1        | 230            |
| 3    | 9            | 3        | 150            |
| 6    | 7            | 1        | 38             |
+------+--------------+----------+----------------+

我尝试使用以下SQL代码:

创建视图...

select t1.* 
  from offers t1
       left join ( select player_id, 
                          team_id, 
                          max(valore) as valore
                     from offers
                 group by player_id, 
                          team_id) t2 
                 on t1.player_id = t2.player_id 
                    and t1.team_id = t2.team_id 
                    and t1.valore = t2.valore

但是结果与第一个表相同...它没有任何改变。 谁能帮我吗?

1 个答案:

答案 0 :(得分:1)

您的预期结果并不暗示team_id子句中的GROUP BY,它实际上是基于player_id的。因此,将其从GROUP BY子句中删除,并将ON子句更改为t1.player_id = t2.player_id and t1.valore = t2.valore

因此,您的查询将是:

create view...
    select t1.*  
    from offers t1 inner join 
        (select player_id, max(valore) as valore
         from offers
         group by player_id
        ) t2 
       on t1.player_id = t2.player_id and
          t1.valore = t2.valore;

但是,我会改为:

create view v1 as
    select o.*
    from offers o
    where valore = (select max(o1.valore)
                    from offer o1
                    where o1.player_id = o.player_id
                   );