我得到以下表格:
col1|col2
Hyd |Bag
kol |Chi
Del |Pat
Bag |Hyd
我需要保留这个
Kol |Chi
Del |Pat
和 我需要保留给定行中的任何一行,即:
Hyd |Bag
Bag |Hyd
我尝试了这个查询:
SELECT * FROM test_kafee a WHERE (SELECT count(*) FROM test_kafee b
WHERE a.Temp1 = b.temp2 AND a.temp2 = b.Temp1 ) = 0
给出了唯一的一个,但是对于重复,我无法使用此查询停止:
SELECT * FROM test_kafee3 a WHERE (SELECT count(*) FROM test_kafee b
WHERE a.Temp1 = b.temp2 AND a.temp2 = b.Temp1 ) > 0
表格可能包含多个副本,如下所示:
COL1 | COL2
Hyd | Bag
kol |志
Del | Pat
袋子| Hyd
Chi | kol
答案 0 :(得分:1)
您希望表中包含所有唯一的组合。
SELECT col1, col2 FROM table1
WHERE col1 <= col2
UNION
SELECT col2, col1 FROM table1
WHERE col2 < col1
UNION
会删除重复项。
答案 1 :(得分:1)
将所需行插入Temp表
INSERT INTO TEMP_TABLE
SELECT col1,col2
FROM YOURTABLE
MINUS
SELECT * FROM
(
SELECT col1,col2
FROM YOURTABLE
INTERSECT
SELECT col2,col1
FROM YOURTABLE;
)
截断你的实际表格
TRUNCATE TABLE YOURTABLE;
插回临时表中的记录
INSERT INTO YOURTABLE
SELECT * FROM TEMP_TABLE;
答案 2 :(得分:0)
如果您正在使用sql server(下次请在数据库中添加标签,以便我们不必猜测),您可以这样做:
DECLARE @tbl table (col1 char(3), col2 char(3))
INSERT INTO @tbl
SELECT 'Hyd', 'Bag'
UNION
SELECT 'kol', 'Chi'
UNION
SELECT 'Del', 'Pat'
UNION
SELECT 'Bag', 'Hyd'
SELECT DISTINCT T1.Col1, T1.Col2
FROM @tbl T1 LEFT JOIN (
SELECT T1.Col1, T1.Col2
FROM @tbl T1 INNER JOIN @tbl T2 ON(T1.Col1 = T2.Col2 AND T1.Col2 = T2.col1)
) T2 ON(T1.col1 = T2.col1 AND T1.col2 = T2.col2)
WHERE T2.col1 IS NULL
UNION ALL
SELECT TOP 1 T1.Col1, T1.Col2
FROM @tbl T1 INNER JOIN
@tbl T2 ON(T1.Col1 = T2.Col2 AND T1.Col2 = T2.col1)