sql查询获取行值的总和

时间:2014-10-10 15:52:01

标签: mysql

我的查询得到像这样的o / p

partyname    bjp      aap         congress   

votes        1        2              2          

但我也需要行总和。以下是我的预期产量。

所有partyname和投票来自数据库,它是动态的。

for ex

 BJP         aap           congress       total

  1             2            2             5


<?php                
$sqltoatl = "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 LIMIT 0 , 1000";

$resulttoatl = mysql_query($sqltoatl);

while ($rowtoatl = mysql_fetch_array($resulttoatl,MYSQL_ASSOC)) {
?>  

<th><?php echo $rowtoatl['PARTYNAME']; ?></th>      
<td><?php echo $rowtoatl['VOTESCOUNT']; ?></td> 
<?php } ?>  

2 个答案:

答案 0 :(得分:1)

不知道您的数据库架构我不太明白您正在进行复杂投票计算的原因。

也许我错过了一些东西,但是如果你想要的是每个派对的票数和总数那么也许这样的东西就是你想要的?

SELECT PARTYNAME, SUM(votes) AS VOTES FROM voter_count GROUP BY Partyname
UNION ALL
SELECT 'Total', SUM(VOTES) AS VOTES FROM voter_count;

它可能看起来像SQL Fiddle

答案 1 :(得分:0)

这样的事情对你有用:

SELECT p.partyId, p.partyName, COUNT(IFNULL(v.bjp,0)) bjpTotal, COUNT(IFNULL(v.aap,0)) aapTotal, COUNT(IFNULL(v.congress,0)) congressTotal, 
      (COUNT(IFNULL(v.bjp,0)) + COUNT(IFNULL(v.aap,0)) + COUNT(IFNULL(v.congress,0))) partyTotal
FROM parties p
LEFT JOIN votes v
    ON p.partyId = v.partyId
GROUP BY p.partyId, p.partyName