分组COUNT的SUM,仅计算最大值并显示最大值

时间:2014-10-10 06:44:22

标签: php mysql

我有一个包含6个字段的表:

    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,选区与'count'和一行'SUM'分组

但它只计算每个选区的最大值,然后显示计数和行数。

以下是上表

的预期输出
partyname       Count
    BJP          2

    AAP          1

bcoz bjp来自nagpur -east和nagpur west。所以显示计数2 并且aap从nagpur - north开始,然后它只显示1个计数。

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

 <?php  
 $state =  $rowdst['state'];
 $sqlst = "SELECT  MAX(votes) AS Vote,constituency,state, district FROM voter_count where state = '$state' group by  constituency, state";
 $resultst = mysql_query($sqlst);
 while($rowst = mysql_fetch_array($resultst,MYSQL_ASSOC))
    {
    ?>  
    <?php
             $vote = $rowst['Vote'];
             $sqlct = "SELECT COUNT($vote) AS counts,partyname,constituency, district FROM voter_count where votes = '$vote' AND state = '$state'";
             $resultct = mysql_query($sqlct);
             $rowct = mysql_fetch_array($resultct,MYSQL_ASSOC)
        ?>    
             <tr>  
              <td><?php echo $rowct['partyname']; ?></td>
              <td><?php echo $rowct['counts']; ?></td>
        </tr>  
<?php } ?>

3 个答案:

答案 0 :(得分:2)

假设您不关心不同方的同一票数(处理同一区内不同方的相同票数将使查询更加复杂,因为您将获得MAX列的不可预测的值在内部查询中):

SELECT RES.PARTYNAME, COUNT(RES.CONSTITUENCY) AS VOTESCOUNT
FROM voter_count RES
JOIN (
    SELECT CONSTITUENCY, MAX(VOTES) AS VOTES
    FROM voter_count
    GROUP BY CONSTITUENCY
) MAXS USING(VOTES, CONSTITUENCY)
GROUP BY PARTYNAME;

首先,内部查询选择votes的最大值。内部查询执行的结果是:

Nagpur-East,1200
Nagpur-North,1500
Nagpur-West,4800

之后,加入最大值并计算区数。

AAP,1
BJP,2

答案 1 :(得分:1)

以下是您的问题的解决方案..希望这会有效..

select t1.partyname as PARTY, count(*) as WinCount
from voter_count t1, voter_count t2 where t1.votes > t2.votes
and t1.constituency=t2.constituency
group by t1.partyname

答案 2 :(得分:0)

在阅读完您的问题之后,很难理解你想要什么作为输出结果

SELECT partyname AS 'Party Name',COUNT(candidatename) AS 'can_count',SUM(votes) AS 'sum'
FROM voter_count 
WHERE votes >= 1500
GROUP BY constituency
ORDER BY can_count DESC;

还要检查此SQL Fiddle Link

希望此查询可以帮助您获得所需的输出..