sql查询从表中选择只有最大值的计数

时间:2014-10-10 07:24:44

标签: php mysql

partyname    state        constituency     candidatename   district    votes

BJP       Maharashtra   Nagpur-East     Nitin Gadkari   Nagpur       1200
AAP       Maharashtra   Nagpur-East     Arvind Kejriwal Nagpur       750
BJP       Maharashtra   Nagpur-West     Vicky           Nagpur       4800
AAP       Maharashtra   Nagpur-West     Lucky           Nagpur       3500
BJP       Maharashtra   Nagpur-North    Rakesh          Nagpur       100
AAP       Maharashtra   Nagpur-North    Ravan          Nagpur       1500

以下是我上面表格的预期输出

查询通过partyname和constituency从投票组中选择最大vlue,并显示如下输出。

partyname       Count

BJP          2

AAP          1

bcoz bjp来自nagpur -east和nagpur west

所以它显示计数2

和aap从nagpur开始 - 北,然后它只显示1个计数。

plz建议我查询......

2 个答案:

答案 0 :(得分:0)

您可以尝试这样:

select max(votes) from tableName group by constituency

Sql fiddle:http://sqlfiddle.com/#!2/ceb017/1

答案 1 :(得分:0)

在MySQL中,您需要一个联接才能获得最多的投票数,然后需要另一个联接才能获得参与者名称和获胜次数:

select c.partyname, count(*) as numwins
from constituency c join
     (select constituency, max(votes) as maxvotes
      from constituency c
      group by constituency
     ) cm
     on c.constituency = cm.constituency and c.votes = cm.votes
group by c.partyname;