Oracle去重函数distinct

distinct用于返回唯一不同的值。

表table1:

idvalue
1a
1a
2b
3b
4c
5c

表table2:

usernamepassword
toms123456
toms123456

 

表table3:

usernamephone
tom10086
jack10010

作用于单列

select distinct value from table1

执行结果如下:

value
a
b
c

 

作用于多列

例1:

select distinct id, name from table1

执行结果如下:

idvalue
1a
2b
3b
4c
5c

通过这个例子可以看出,多列去重是根据写在distinct后面的各个字段来去重的(当这几个字段所有的列的值都相同时才会被认为是重复数据)。

例2:

select distinct username, password from table2

执行结果如下:

usernamepassword
toms123456
toms123456

执行结果为两行,这说明distinct是分别作用了username和password列,而不是把这两列的值“拼接”后再去重的。

 

多表查询

select distinct o.username from table2 o , table3 t  where  o.username = t.username ;

执行结果如下:

username
tom

 

此外还需要注意一下几点:

1.distinct必须放在开头,如果不放在开头会报错

select id, distinct value from table1;   --会提示错误

2.多表查询时,如果表中有相同字段名,需指定是那张表的字段

select distinct username from table2 o , table3 t  where  o.username = t.username    --会提示错误

3.COUNT统计单字段

select count(distinct value) from table1;  --表中value去重后的数目

4.COUNT统计多字段

count是不能统计多个字段的,可以使用嵌套查询解决:

select count(*) from (select distinct username, password from table2) as t2;

 如果这样查询:select count(distinct value, id) from table1;会报错

5.显示字段

显示的字段只能是distinct指定的字段

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值