我的表格如下:
ID from to
1 X Y
2 Y X
3 Z X
4 R L
请注意前两行:
1 X Y
2 Y X
我想要的是阻止反向列/不同列上的相同值,或from != to
我希望SQL返回:
ID from to
1 X Y
3 Z X
4 R L
SQL可以这样做吗?
答案 0 :(得分:3)
DISTINCT
子句不是这项工作的正确工具,但您可以轻松地消除"重复"像这样排队:
select *
from Table1 AS T1
where not exists (
select 1
from Table1 AS T2
where T1.from = T2.to
and T1.to = t2.from
and T1.id > T2.id
)
答案 1 :(得分:2)
我将列组合在一起并将它们排序。 然后我使用group by删除副本。这里的Se演示:http://sqlfiddle.com/#!17/72d28/17
Select tbl.*
from tbl
Join
(Select min(id) as id
From (Select id,
Case when fromcol > tocol then fromcol || tocol
else tocol || fromcol end as combined
From tbl) s
Group by combined) t
On tbl.id = t.id;
Result:
id fromcol tocol
1 x y
3 z x
4 r l
答案 2 :(得分:1)
您可以按from
和to
的正常组合进行分组:
select min(id) as id,
least("from", "to") as "from",
greatest("from", "to") as "to"
from the_table
group by least("from", "to"), greatest("from", "to")
order by 1;
答案 3 :(得分:0)
您还可以使用least()
和greatest()
函数查找两列中的最小值和最大值
select * from table t
where id in (
select min(id) from table
group by least(from, to), greatest(from, to)
)