MAX(SUM(投票))|只获得胜利者

时间:2011-07-12 11:38:34

标签: mysql sql

我想在mysql表中只获得胜利者。

SELECT mayor_id, local_unit_id, Value FROM 
   (SELECT mayor_id,  local_unit_id, SUM(  `votes` ) AS  'Value' 
    FROM mayorresults 
    GROUP BY  `mayor_id`) AS t1
    ORDER BY  `t1`.`local_unit_id` ASC

想法是先投票然后获得最大数量,在这种情况下是赢家。

通过这个查询,我可以得到所有,但不仅仅是获胜者。

我想得到MAX(SUM(投票)),但它不会像这样工作。

编辑:我希望获得每个本地单位的获胜者

例如

local_unit_id    mayor_id    votes
 1                25          8562
 2                534         18562

2 个答案:

答案 0 :(得分:1)

你试过了吗?

SELECT mayor_id, local_unit_id, MAX(Value) FROM 
   (SELECT mayor_id,  local_unit_id, SUM(  `votes` ) AS  'Value' 
    FROM mayorresults 
    GROUP BY  `mayor_id`) AS t1
    ORDER BY  `t1`.`local_unit_id` ASC

您不能拥有总和的最大值。您可以获得子查询的最大总和。

答案 1 :(得分:1)

在解释之后更新:

SELECT grp.local_unit_id, grp.mayor_id, grp.Value
FROM  
    ( SELECT  local_unit_id, mayor_id, SUM( votes ) AS Value 
      FROM mayorresults 
      GROUP BY local_unit_id, mayor_id
    ) AS grp
  JOIN
    ( SELECT local_unit_id, MAX(Value) AS Value
      FROM 
        ( SELECT  local_unit_id, mayor_id, SUM( votes ) AS Value 
          FROM mayorresults 
          GROUP BY local_unit_id, mayor_id
        ) AS grp
      GROUP BY local_unit_id
    ) AS grp2
    ON  grp2.local_unit_id = grp.local_unit_id
    AND grp2.Value = grp.Value
ORDER BY local_unit ASC