相关文章推荐
听话的领带  ·  groovy regex find all ...·  1 年前    · 
小眼睛的金鱼  ·  (Github) "Testing ...·  1 年前    · 
安静的打火机  ·  how to solve ...·  1 年前    · 

由于小王没有迟到过,所以缺勤流水表格当中没有小王的记录,如果我们这样搜索:

1 select name, count(*) from {缺勤流水表格} where name in (小明,小王,小红) group by name

那么我们得到的将是:

小明  3

小红  4

并没有小王的记录!

解决方法 -- 运用CASE WHEN语句:

1 slelct name, count(case when name in (小明,小王,小红) then 1 else 0 end)  from {缺勤流水表格}  group by name

得到的结果为:

小明  3

小王  0

小红  4

另外说一下,不是每中情况下都能找到这样的 case when语句,也有可能需要我们对sql语句改动一下,例如:

1 select t1.name,  ifnull( t2.count,0)  from {缺勤流水表格} as t1
3 join
5 (select id, name, count(*) as count from {缺勤流水表格} where name in (小明,小王,小红) group by name) as t2
7 on t1.id = t2.id