-------------------------------------
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子句计数
例如,如果我的条件是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",
)
感谢任何帮助,谢谢
答案 0 :(得分:1)
使用SUM()
计算符合所需条件的行数。
SELECT class, SUM(class = "First") AS count
FROM students
GROUP BY class
答案 1 :(得分:0)
SELECT class
,count(case when class='first' then 1 else null end)
FROM students
GROUP BY class
答案 2 :(得分:0)
SELECT class, IF(class='first',count(1),0)
FROM students
GROUP BY class
MySQL有一个IF()
函数,它接受三个参数,一个测试,结果为true,结果为false。因为您只想计算类是否为'first',所以如果测试失败则返回0并返回计数(如果测试通过,我更喜欢在计算行时计算1)。
在MsSQL中,相同的功能是IIF()
。