开发者

MAX (SUM(votes)) | get only winners

I want to get only winners in mysql table.

SELECT mayor_id, local_unit_i开发者_如何学God, 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

Idea is to Sum votes first then get only largest number, in this case the winner.

With this query I can get all, but not just the winners.

I want MAX(SUM(votes)) to get, but It doesn't work like this.

EDIT: I want to get winners for each localunit

eg.

local_unit_id    mayor_id    votes
 1                25          8562
 2                534         18562


Update, after the explanations:

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


Have you tried:

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

You can't have the max value of a sum. You can have the max sum of a subquery.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜