1.今天在使用count函数带条件进行数据统计时发现了一个问题
--根据类型统计总数和不同状态的数量
select execute_type,
count(1) totalNum,
count(execute_status = '0') unexecute
from nurse_orders_execute
group by execute_type
2.然后发现报错了
然后网上搜索发现count函数待条件需要在条件后加一个or null,如下
select execute_type,
count(1) totalNum,
count(execute_status = '0' or null) unexecute
from nurse_orders_execute
group by execute_type
需要添加or null的原因是,count函数判断前面的条件为true才会统计数量,而条件为false时会变成count(null),才不会进行统计
详细可参考:
https://blog.csdn.net/qq_32719287/article/details/79513164
3.但是我发现还是会报一样的错,后来继续查资料发现Oracle的count函数带条件的写法不一样
Oracle他不能在count函数里面直接写像execute_status = '0’这样的条件语句,他需要使用decode或者case when这样的函数,修改之后sql如下:
--最终正确的sql语句
select execute_type,
count(1) totalNum,
count(decode(execute_status,'0',1,null)) unexecute
from nurse_orders_execute
group by execute_type
和or null类似的,需要进行条件判断,符合条件的返回1,不符合条件的返回null。