php - 使用仅用于计数的 where 子句获取不同行及其记录计数

标签 php mysql sql database

-------------------------------------
Name of Student       |      class   
-------------------------------------
S1                            First
S11                           First
S12                           First
S13                           First
S2                            Second
S3                            Third
S31                           Third
-------------------------------------

现在我通过以下查询获得了不同的类及其每个计数

SELECT class,count(*) FROM students GROUP BY class

我明白了,一切都很好

array(
       "class"=> "First", "count"=>"4",
       "class"=> "Second", "count"=>"1",
       "class"=> "Third", "count"=>"2",
    ) 

但我只想将 where 条件应用于计数,因此我想要所有不同的类,并根据 where 子句进行计数

例如,如果我的条件是 class="First"

SELECT class,count(*) FROM students where class="First" GROUP BY class

该查询给了我这个

array(
       "class"=> "First", "count"=>"4"
    )

但我想要所有不同的类,所以我的预期结果如下

array(
       "class"=> "First", "count"=>"4",
       "class"=> "Second", "count"=>"0",
       "class"=> "Third", "count"=>"0",
    )  

感谢任何帮助,谢谢

最佳答案

使用SUM()计算符合所需条件的行数。

SELECT class, SUM(class = "First") AS count
FROM students
GROUP BY class

关于php - 使用仅用于计数的 where 子句获取不同行及其记录计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162333/

相关文章:

mysql - 输出排序不正确

mysql - 为什么其次是关系影响结果?

php - 黑色菱形/问号替换 WordPress 中的随机字符

php - 如何在 Facebook 注册插件中添加 Conceal 字段?

php - 服务器重启后内存缓存数据是否保存?

mysql - 具有相同 GUID 的多个列,获取每个 GUID 的最新列

javascript - 带 Action 的倒数计时器

PHP PostgreSQL 数组到字符串

sql - 如何一次执行 2 个更新语句?

mysql - 如何修复 SQL 错误 1064?