首页 技术 正文
技术 2022年11月19日
0 收藏 773 点赞 4,143 浏览 1685 个字

select语句中,使用distinct关键字,在处理select list后,结果表可以选择消除重复的行。在SELECT之后直接写入DISTINCT关键字以指定此关键字:

SELECT DISTINCT select_list ...

(可以使用关键字ALL代替DISTINCT来指定保留所有行的默认行为)

 

显然,如果两行至少有一个列值不同,则认为它们是不同的。在此比较中,将空值视为相等。

 

另外,一个任意表达式可以确定哪些行被认为是不同的:

SELECT DISTINCT ON (expression [, expression ...]) select_list ...

这里的expression是一个针对所有行求值的任意值表达式。 一组所有表达式均相等的行被视为重复行,并且仅该集合的第一行保留在输出中。请注意,除非查询在足够的列上排序以保证到达DISTINCT过滤器的行的唯一顺序,否则集合的“第一行”是不可预测的。(DISTINCT ON处理在ORDER BY排序之后进行)

DISTINCT ON子句不是SQL标准的一部分,有时由于其结果的不确定性而有时被认为是不良样式。通过明智地使用GROUP BYFROM中的子查询,可以避免这种构造,但是它通常是最方便的选择。

create table t_distinct(a int ,b int ,c int);
insert into t_distinct values(1,2,3);
insert into t_distinct values(2,3,4);
insert into t_distinct values(3,4,5);insert into t_distinct values(2,2,3);
insert into t_distinct values(3,3,4);
insert into t_distinct values(4,4,5); insert into t_distinct(a,b) values(5,6);
insert into t_distinct(a,b) values(5,6);
insert into t_distinct(a,b) values(6,7);

  

1.返回所有记录:

# select a,b,c from t_distinct;
a | b | c
---+---+---
1 | 2 | 3
2 | 3 | 4
3 | 4 | 5
2 | 2 | 3
3 | 3 | 4
4 | 4 | 5
5 | 6 |
5 | 6 |
6 | 7 |
(9 rows)# select all a,b,c from t_distinct;
a | b | c
---+---+---
1 | 2 | 3
2 | 3 | 4
3 | 4 | 5
2 | 2 | 3
3 | 3 | 4
4 | 4 | 5
5 | 6 |
5 | 6 |
6 | 7 |
(9 rows)

  

2.返回 a,b,c 唯一值。(这里NULL视为相等)

# select distinct a,b,c from t_distinct;
a | b | c
---+---+---
2 | 2 | 3
5 | 6 |
1 | 2 | 3
6 | 7 |
3 | 3 | 4
4 | 4 | 5
3 | 4 | 5
2 | 3 | 4
(8 rows)

  

3.返回a唯一的任意行

# select distinct on (a) a,b,c from t_distinct;
a | b | c
---+---+---
1 | 2 | 3
2 | 2 | 3
3 | 3 | 4
4 | 4 | 5
5 | 6 |
6 | 7 |
(6 rows)

使用窗口函数可以达到类似效果,但是可以确定返回哪行,因此也更慢一些:

# select * from (select row_number() over (partition by a) as rn, * from t_distinct) t where rn=1;
rn | a | b | c
----+---+---+---
1 | 1 | 2 | 3
1 | 2 | 2 | 3
1 | 3 | 3 | 4
1 | 4 | 4 | 5
1 | 5 | 6 |
1 | 6 | 7 |
(6 rows)

  

# select distinct on (a,b) a,b,c from t_distinct;
a | b | c
---+---+---
1 | 2 | 3
2 | 2 | 3
2 | 3 | 4
3 | 3 | 4
3 | 4 | 5
4 | 4 | 5
5 | 6 |
6 | 7 |
(8 rows)#这里NULL视为相等
# select distinct on (c) a,b,c from t_distinct;
a | b | c
---+---+---
1 | 2 | 3
3 | 3 | 4
3 | 4 | 5
5 | 6 |
(4 rows)

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,557
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898