MYSQL count only those students with number 1

时间:2016-09-14 01:53:18

标签: mysql

i would like construct a query to count the number of student who don't have number 0.

assuming i have 2 tables

students
*student_id
*name

Number
*number_id
*student_id
*number

| Student 1 |
1
1
1
1
| Student 2 |
1
1
1
1
| Student 3 |
1
0
1
0

|Student 4 |
0
1
1
1

So the result should be. student without zero = 2
student with zero = 2

2 个答案:

答案 0 :(得分:0)

此答案假设您的表格具有以下结构:

id | value
1  |   1
1  |   1
1  |   1
1  |   1
2  |   1
etc...

SELECT id
FROM yourTable
GROUP BY id
HAVING SUM(CASE WHEN value = 0 THEN 1 ELSE 0 END) = 0

答案 1 :(得分:0)

这样的事情可能会返回指定的结果:

SELECT CONCAT('student without zero = '
            , ( SELECT SUM(1)
                  FROM ( SELECT t.`some_identifier`
                           FROM `sometable` t
                          GROUP BY t.`some_identifier`
                         HAVING SUM(IF(t.`some_col`=0,1,0)) = 0
                       )
              )
            , '\n'
            , 'student with zero = '
            , ( SELECT SUM(1)
                  FROM ( SELECT z.`some_identifier`
                           FROM `sometable` z
                          WHERE z.`some_col` = 0
                          GROUP BY z.`some_identifier`
                       )
              )
       ) AS `result`

只需将some_table替换为表的名称,some_col替换为包含1和0值的列的名称,将some_identifier替换为包含{{1}的列1}},Student 1等值。

这应该返回一行,如下所示:

Student 2