sql查询获取计数值的总和

时间:2014-10-11 09:03:43

标签: php mysql

   aap      bjp       congress          sum
    1        2           5               8

我想显示投票数量。,如上表输出。

下面是我的SQL查询

PLZ建议我如何获得echo votescount的总和。

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

4 个答案:

答案 0 :(得分:1)

我认为以下查询应该适合您:

SELECT SUM(x.VOTESCOUNT) AS VOTESUM FROM ( 
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
) x;

VOTESUM将为您提供VOTESCOUNT的总和

答案 1 :(得分:0)

根据你的表格,

SELECT SUM(partyname) AS total_parties, SUM(votes) AS total_votes FROM table_name;

这是你想要的吗?你的问题不明确&查询与描述无关......

sql query to calculate sum of agroup counts

的副本

答案 2 :(得分:0)

如果您的列值是每个定义的,那么您可以使用下面的静态查询

SELECT
       count(CASE WHEN partyname = 'BJP' THEN pagecount END) `BJP`,
       count(CASE WHEN partyname = 'AAP' THEN pagecount END) `AAP`,
       count(CASE WHEN partyname = 'Other' THEN pagecount END) `Other` ,

       count(CASE WHEN partyname = 'BJP' THEN pagecount END) +
       count(CASE WHEN partyname = 'AAP' THEN pagecount END)+ 
       count(CASE WHEN partyname = 'Other' THEN pagecount END) `Sum` 
  FROM test_vote 

您可以使用Fiddle链接,我使用示例数据创建。

如果你想拥有动态列,那么你可以使用PIVOT表,它将以表格格式提供动态输出。

希望这会有所帮助!

答案 3 :(得分:0)

从partyname中选择(从表中选择sum(votes),partyName,count(id)from table group

从表格中选择总和(投票)//给予总票数//休息给予党名明智的投票