Sql 在两列中选择具有相似数据的不同数据
我有一张桌子 使用此示例数据:Sql 在两列中选择具有相似数据的不同数据,sql,oracle10g,distinct,Sql,Oracle10g,Distinct,我有一张桌子 使用此示例数据: ('Pune','Mumbai',128); ('Mumbai','Pune',128); ('Pune','Nashik',200); ('Nashik','Pune',200); ('Nashik','Mumbai',250); ('Nashik','Mumbai',250); 我只想选择一次城市组合,即从孟买浦那和孟买浦那只能选择一行 我试着使用self-join,但是没有用。所以,如果你能提供一个查询,请 提前感谢。如果c2>c1,请使用not exis
('Pune','Mumbai',128);
('Mumbai','Pune',128);
('Pune','Nashik',200);
('Nashik','Pune',200);
('Nashik','Mumbai',250);
('Nashik','Mumbai',250);
我只想选择一次城市组合,即从孟买浦那和孟买浦那只能选择一行
我试着使用self-join,但是没有用。所以,如果你能提供一个查询,请
提前感谢。如果c2>c1,请使用not exists检查切换的c1/c2列是否存在切换组合:
select distinct c1, c2, dist
from XXXTEST t1
where c1 < c2
or not exists (select * from XXXTEST t2
where t1.c1 = t2.c2 and t1.c2 = t2.c1);
执行为:
SQL>CREATE TABLE XXXTEST (C1 VARCHAR(10),C2 VARCHAR(10), dist integer);
SQL>INSERT INTO xxxtest VALUES ('Pune','Mumbai',128);
SQL>
SQL>INSERT INTO xxxtest VALUES ('Mumbai','Pune',128);
SQL>INSERT INTO xxxtest VALUES ('Pune','Nashik',200);
SQL>INSERT INTO xxxtest VALUES ('Nashik','Pune',200);
SQL>INSERT INTO xxxtest VALUES ('Nashik','Mumbai',250);
SQL>INSERT INTO xxxtest VALUES ('Nashik','Mumbai',250);
SQL> select distinct c1, c2, dist
SQL& from XXXTEST t1
SQL& where c1 < c2
SQL& or not exists (select * from XXXTEST t2
SQL& where t1.c1 = t2.c2 and t1.c2 = t2.c1);
C1 C2 dist
========== ========== ===========
Mumbai Pune 128
Nashik Mumbai 250
Nashik Pune 200
3 rows found
分层方法:
另外,假设城市之间的距离是唯一的,我认为你可以简单地选择不同的距离,而不是将其与城市及其组合复杂化
分析方法:
您可以按字母顺序对城市进行排序,然后使用简单的:
这个问题是不正确的。它将只为精确的副本提供一个唯一的行。完全不同于OP的要求。是的,当然。早上在这里太早了。。。我要一杯咖啡,然后编辑。
SQL>CREATE TABLE XXXTEST (C1 VARCHAR(10),C2 VARCHAR(10), dist integer);
SQL>INSERT INTO xxxtest VALUES ('Pune','Mumbai',128);
SQL>
SQL>INSERT INTO xxxtest VALUES ('Mumbai','Pune',128);
SQL>INSERT INTO xxxtest VALUES ('Pune','Nashik',200);
SQL>INSERT INTO xxxtest VALUES ('Nashik','Pune',200);
SQL>INSERT INTO xxxtest VALUES ('Nashik','Mumbai',250);
SQL>INSERT INTO xxxtest VALUES ('Nashik','Mumbai',250);
SQL> select distinct c1, c2, dist
SQL& from XXXTEST t1
SQL& where c1 < c2
SQL& or not exists (select * from XXXTEST t2
SQL& where t1.c1 = t2.c2 and t1.c2 = t2.c1);
C1 C2 dist
========== ========== ===========
Mumbai Pune 128
Nashik Mumbai 250
Nashik Pune 200
3 rows found
SQL> SELECT DISTINCT c1,
2 c2,
3 dist
4 FROM
5 ( SELECT c1, c2, dist FROM xxxtest CONNECT BY nocycle prior c1 = c2
6 )
7 WHERE c1 > c2
8 /
C1 C2 DIST
---------- ---------- ----------
Pune Mumbai 128
Nashik Mumbai 250
Pune Nashik 200
SQL>
SQL> WITH DATA AS
2 (SELECT c1,
3 c2,
4 dist,
5 row_number() over(partition BY dist order by dist) rn
6 FROM xxxtest
7 )
8 SELECT c1, c2, dist FROM DATA WHERE rn = 1
9 /
C1 C2 DIST
---------- ---------- ----------
Pune Mumbai 128
Pune Nashik 200
Nashik Mumbai 250
SQL>
select distinct
least(c1, c2) as c1,
greatest(c1,c2) as c2,
dist
from XXXTEST