MySQL将结果多个结果值合并为2

时间:2016-02-20 13:58:53

标签: mysql

我试图将值组合起来,如果0则是第一个值,如果是1,2或3那么它是第二个值

id   student   IQ
1    one       0
2    two       1
3    three     2
4    four      3
5    five      0

我想要的是告诉我有2名学生IQ=0而3名学生> 0

编写此mysql查询的最简单方法是什么?

3 个答案:

答案 0 :(得分:2)

我认为你想要条件聚合:

select sum(iq = 0), sum(iq > 0)
from t;

答案 1 :(得分:1)

您可以尝试:

SELECT CASE WHEN IQ = 0 THEN 1 
              WHEN IQ > 0 THEN 2
         END,
         COUNT(*)
FROM mytable
GROUP BY CASE WHEN IQ = 0 THEN 1 
              WHEN IQ > 0 THEN 2
         END

或者,如果IQ是正数:

SELECT IF(IQ = 0, IQ, 1),
       COUNT(*)
FROM mytable
GROUP BY IF(IQ = 0, IQ, 1)

答案 2 :(得分:0)

怎么样

SELECT COUNT(CASE WHEN iq = 0 THEN 1 ELSE NULL END) as studentsWithZeroIq,
       COUNT(CASE WHEN iq > 0 THEN 1 ELSE NULL END) as studentsWithNonZeroIq
FROM mytable;