0
点赞
收藏
分享

微信扫一扫

oracle 使用count()函数进行分组计数时所踩的坑!

 

1.情景展示

  需要对id_card字段按字符长度进行分组统计并进行计数。

2.错误方式

  第一步:统计出id_card字段共存在几种情况。

  第一种方式:distinct

oracle 使用count()函数进行分组计数时所踩的坑!_字段

  第二种方式:group by

oracle 使用count()函数进行分组计数时所踩的坑!_oracle_02

  第二步:分组计数

  计数只能通过group by来实现。

oracle 使用count()函数进行分组计数时所踩的坑!_字段_03

  问题就在于:

  当id_card字段内容为空(null)时,这个地方计数实际是错误的!

  因为count()函数自动将字段id_card的为null的值去掉了!而实际需要将该字段为空的行数据也统计在内。

3.解决方案

  使用count(1)解决。

oracle 使用count()函数进行分组计数时所踩的坑!_数据_04

  说明:

count(1)和count(*),这两个函数计数的时候,都会将null统计在内,也包括重复记录;

  count(字段名) ,这个函数会自动将该字段值为null的记录排除在外,也包括重复记录。

2021年9月27日16:32:48

4.扩展

  现有一组数据,字段名称为:isupload,其值至少有3种情况,分别为:1,2,空he可能为其它值;

  现在需要将不是1且不是2的内容筛选出来,我们第一想要的SQL是酱紫的:

select count(1) from table_name where isupload <> 1 and  isupload <> 2;

  查询结果,和总数匹配对不上;

select count(1) from table_name;
select count(1) from table_name where isupload = 1;
select count(1) from table_name where isupload = 2;

  经排查,发现:第一个SQL语句将字段值为null的数据排除在外了。

select count(1) c from table_name where isupload <> 1 and  isupload <> 2
union all
select count(1) c from table_name where isupload is null;

  这样,才是字段值既不为1,也不为2的数据。

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!


举报

相关推荐

0 条评论