删除oracle中两列组合的重复项
Deleting duplicates on combination of two columns in oracle
我有一个 table 例如:
端口 Table
S No
A Port
B port
1
80
100
2
90
110
3
100
80
4
94
106
我要删除记录号。 3 因为它与记录号具有相同的组合。 1 如何在 Oracle 中执行此操作?
在 mysql 试过这个,做一些 test/scenarios
SELECT P1.* FROM port_tbl AS P1
LEFT JOIN port_tbl AS P2 ON P1.port1 = P2.port2 OR P1.port2 = P2.port1
WHERE P1.id < P2.id OR ISNULL(P2.id)
ORDER BY P1.id;
您可以使用单个 MERGE
语句和 ROW_NUMBER
分析函数结合 GREATEST
和 LEAST
来查找和删除重复项:
MERGE INTO table_name dst
USING (
SELECT ROWID rid,
ROW_NUMBER() OVER (
PARTITION BY LEAST(A_Port, B_Port), GREATEST(A_Port, B_Port)
ORDER BY S_no
) AS rn
FROM table_name
) src
ON (dst.ROWID = src.rid AND src.rn > 1)
WHEN MATCHED THEN
UPDATE SET A_port = NULL
DELETE WHERE 1 = 1;
其中,对于您的样本数据:
CREATE TABLE table_name (S_No, A_Port, B_port) AS
SELECT 1, 80, 100 FROM DUAL UNION ALL
SELECT 2, 90, 110 FROM DUAL UNION ALL
SELECT 3, 100, 80 FROM DUAL UNION ALL
SELECT 4, 94, 106 FROM DUAL;
将删除第 3 行。
db<>fiddle here
我有一个 table 例如: 端口 Table
S No | A Port | B port |
---|---|---|
1 | 80 | 100 |
2 | 90 | 110 |
3 | 100 | 80 |
4 | 94 | 106 |
我要删除记录号。 3 因为它与记录号具有相同的组合。 1 如何在 Oracle 中执行此操作?
在 mysql 试过这个,做一些 test/scenarios
SELECT P1.* FROM port_tbl AS P1
LEFT JOIN port_tbl AS P2 ON P1.port1 = P2.port2 OR P1.port2 = P2.port1
WHERE P1.id < P2.id OR ISNULL(P2.id)
ORDER BY P1.id;
您可以使用单个 MERGE
语句和 ROW_NUMBER
分析函数结合 GREATEST
和 LEAST
来查找和删除重复项:
MERGE INTO table_name dst
USING (
SELECT ROWID rid,
ROW_NUMBER() OVER (
PARTITION BY LEAST(A_Port, B_Port), GREATEST(A_Port, B_Port)
ORDER BY S_no
) AS rn
FROM table_name
) src
ON (dst.ROWID = src.rid AND src.rn > 1)
WHEN MATCHED THEN
UPDATE SET A_port = NULL
DELETE WHERE 1 = 1;
其中,对于您的样本数据:
CREATE TABLE table_name (S_No, A_Port, B_port) AS
SELECT 1, 80, 100 FROM DUAL UNION ALL
SELECT 2, 90, 110 FROM DUAL UNION ALL
SELECT 3, 100, 80 FROM DUAL UNION ALL
SELECT 4, 94, 106 FROM DUAL;
将删除第 3 行。
db<>fiddle here