子查询中带有count然后报不是单分组函数的问题

例如一个A表,我统计了A表的总行数,然后我想在结果中一同显示A表非空的行数,我在子查询用count()的时候就报不是单分组函数,请问这个问题该怎样去解决呢

select count(1),
          (select count(1) from A where A.a is not null)
from A


SELECT (SELECT COUNT(*) FROM A),(SELECT COUNT(*) FROM A WHERE A.a is not null)

select 
  count(1) 总行数
  count(case when a.某个字段 is not null then 1 else null end) 不为空行数,
  count(case when a.某个字段 is null then 1 else null end) 为空行数,
from A
 

如果是mysql数据库执行是没有问题的,不知道你用的什么数据库
最简单的解决方案可以拆成两个sql分开执行

能只查一次表就不要查两次

select count(1),
          count(A.a)
from A

count某个字段的时候,对于空值是不会进行计数统计的


题主说要按条件进行统计

select count(1),
          count( case when a.a=1 then 1 end )
from A

此处的case when 对于a.a=1都会转化成一个非空的值,比如1,当然也可以是其他值,然后不满足此条件的都会返回空,结合上一点提到的,count字段只会对非空值进行统计