SQL去重问题(应该是比较高级的去重?)

原题:
List the names of all the pairs of U.S. counties that touch each other only in a point (or multiple points, but not lines). Make sure to list each pair only once, and sort results alphabetically by the name of the first county in a pair and then by the name of the second county.

问题:
如何保证每一对只显示一次?(make sure to list each pair only once)。

举例:
返回的记录是:
1 A B
2 A C
3 A D
4 B A

我们视 1 和 4 是重复的, 如何去除

SELECT (CASE WHEN 第一列<第二列 THEN 第一列+第二列 ELSE 第二列+第一列 END) as AB from table group by AB

要么你根据某个字段 使用distinct函数去除重复 或者是group by 一下

使用distinct 或者group by

可以进行取MD5值再进行distinct

后面追加一列,内容为:把第二列和第三列先排序(case when) 后拼接(concat) 按照追加列进行distincet 或 group by

如果就是只有2列, 可以使用 case when 来进行 行内排序再进行distinct 去重复

create table testtable_csdn2 (id int,a varchar(10),b varchar(10))
INSERT INTO testtable_csdn2 (id, a, b) VALUES (1, 'a', 'b');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (2, 'o', 'y');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (3, 'i', 'u');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (4, 'f', 'b');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (5, 'a', 'w');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (6, 'y', 'o');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (7, 'B', 'a');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (8, 'w', 'a');
INSERT INTO testtable_csdn2 (id, a, b) VALUES (9, 'b', 'a');
图片说明
select * from testtable_csdn2 where id in(select max(id) from testtable_csdn2 group by ascii(a)+ascii(b))
图片说明

--这样解决 假设DUAL表有两列 分为我1 和 2,有两行数据21,12。查询结果应该1
select count(1)from(
select 2||1 from dual
union
select 1||2 from dual
minus
select 1||2 from dual)

用distinct来消除重复