mysql子查询并具有子查询的最大值

时间:2012-05-05 09:29:44

标签: mysql subquery max having

SELECT plaka, party_id, sum(inf) i 
  FROM party_sehir
 GROUP BY party_id, plaka

这是我的子查询,结果是:

plaka   party_id   i 
34      1          42
34      2          9
35      1          11
35      2          26

从这些结果中,我希望得到i和行plaka的最大party_id,如下所示:

plaka  party_id    i 
34     1           42
35     2           26

我的意思是每个plaka的最大值。我也尝试过:

SELECT * 
  FROM ( SELECT plaka, party_id, sum(inf) i 
           FROM party_sehir
          GROUP BY party_id, plaka ) t1 
 GROUP BY plaka  
HAVING i >= max(i)

没用;有人能帮忙吗?

谢谢

2 个答案:

答案 0 :(得分:2)

需要更长的查询,例如

select plaka,party_id, i 
from
(SELECT plaka,party_id, sum(inf) i FROM party_sehir
 GROUP BY  party_id, plaka) sum_group
where (i,plaka) in (
SELECT max(i), plaka
 FROM (SELECT plaka,party_id, sum(inf) i FROM party_sehir
 GROUP BY  party_id, plaka) t1 group by plaka ) 

答案 1 :(得分:0)

请尝试分组以获取解决方案

SELECT plaka ,party_id   , max( `i` ) FROM `party_sehir` GROUP BY `plaka`

OR

SELECT * FROM `party_sehir` AS s1 WHERE s1.i = (SELECT max( `i` ) FROM party_sehir AS  
   s2  WHERE s1.plaka = s2.plaka ) GROUP BY `plaka`