SQL选择两个不同列上的区别

时间:2018-03-28 03:21:36

标签: sql postgresql

我的表格如下:

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可以这样做吗?

4 个答案:

答案 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 
  )

以下是工作示例:http://sqlfiddle.com/#!15/89047/1

答案 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)

您可以按fromto的正常组合进行分组:

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;

在线示例:http://rextester.com/ZTRR72072

答案 3 :(得分:0)

您还可以使用least()greatest()函数查找两列中的最小值和最大值

select * from table t
where id in (
       select min(id) from table 
       group by least(from, to), greatest(from, to)
)