MySQL中count(distinct col...)组合使用的注意要点

第一步:数据准备

mysql> select * from my_student;
+----+------------+-----------+--------+--------+
| id | number     | name      | sex    | addr   |
+----+------------+-----------+--------+--------+
|  1 | itcast0001 | Jim       | female | 北京   |
|  2 | itcast0002 | HanMeimei | female | 上海   |
|  3 | itcast0003 | Kate      | female | NULL   |
|  4 | itcast0004 | Tom       | male   | NULL   |
|  5 | itcast0005 | LinTao    | male   | NULL   |
|  6 | itcast0006 | 张越      | 女     | NULL   |
+----+------------+-----------+--------+--------+
6 rows in set (0.00 sec)

第二步:数据验证

1.distinct单字段去重

mysql> select distinct addr from my_student;
+--------+
| addr   |
+--------+
| 北京   |
| 上海   |
| NULL   |
+--------+
3 rows in set (0.00 sec)

2.count和distinct配合使用

        1).count(distinct col) 计算该列除 NULL 之外的不重复行数。

    mysql> select count(distinct addr) from my_student;							①
	+----------------------+
	| count(distinct addr) |
	+----------------------+
	|                    2 |
	+----------------------+
	1 row in set (0.00 sec)
	
	-- 把上述SQL改写成 select count(1) from (select distinct col from ...) a; 
	mysql> select count(1) from (select distinct addr from my_student) a;		②
	+----------+
	| count(1) |
	+----------+
	|        3 |
	+----------+
	1 row in set (0.00 sec)

                注意比较①和②的结果,是不同的.

        2).count(distinct col1, col2) 如果其中一列全为 NULL,那么即使另一列有不同的值,也返回为 0。

    mysql> select distinct sex,addr from my_student;
	+--------+--------+
	| sex    | addr   |
	+--------+--------+
	| female | 北京   |
	| female | 上海   |
	| female | NULL   |
	| male   | NULL   |
	| 女     | NULL   |
	+--------+--------+
	5 rows in set (0.00 sec)
	
	mysql> select count(distinct sex,addr) from my_student;                     ③
	+--------------------------+
	| count(distinct sex,addr) |
	+--------------------------+
	|                        2 |
	+--------------------------+
	1 row in set (0.00 sec)

	mysql> select count(1) from (select distinct sex,addr from my_student) a;	④
	+----------+
	| count(1) |
	+----------+
	|        5 |
	+----------+
	1 row in set (0.00 sec)

                注意比较③和④的结果,也是不同的.

3.上述同样的操作在oracle数据库验证
    1).针对上述1)的场景在oracle数据库中验证后,count(distinct col)也是会计算该列除 NULL 之外的不重复行数,同MySQL一样
    2).针对上述2)的场景,count(distinct col1, col2)的写法在oracle数据库中不支持.

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值