每个项目的MySQL计数

时间:2013-03-23 12:51:15

标签: mysql sql

我正在尝试创建一个mysql查询,它将按照以下方式计算每个项目的零和一个数量: 表:

    ID    |    PollID    |    Value
------------------------------------
    1     |      1       |     1
    2     |      1       |     1
    3     |      2       |     0
    4     |      2       |     1
    5     |      1       |     0

我想要的结果是:

    Poll    |    one    |    zero
----------------------------------
      1     |     2     |     1
      2     |     1     |     1

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

这是MySQL中最短的答案,因为它支持布尔算法。

SELECT  PollID,
        SUM(value = 1) AS `One`,
        SUM(value = 0) AS `Zero`
FROM    tableName
GROUP   BY PollID

答案 1 :(得分:0)

试试这个

      select table.pollid,
      Switch(table.value Like 1, 1)AS one,
      Switch(table.value Like 0, 1)AS zero       
      from table
      group by pollid

答案 2 :(得分:0)

select z.pollid,z.ones,s.zeros 
  from (select a.pollid,count(a.value) as ones from test a
    where a.value=1
group by a.pollid) z   
left join   
    (select b.pollid,count(b.value) as zeros from test b  
     where b.value=0 group by b.pollid) s    
on z.pollid=s.pollid;