我有一个表“Dummy”,其中包含列"col1“和”col2“。
如何从(col1,col2)中找到唯一对。例如,在上表中,我如何仅获得(a,b)或(b,a)作为我的输出,而不是同时获得(a,b)和(b,a)。
select
distinct
col1
col2
from
dummy
where
dummy.col1 < dummy.col2
group by
col1,
col2;上面的查询是错误的,因为它遗漏了对(d,c)。

发布于 2018-02-23 06:28:10
使用least和greatest。
select least(col1,col2),greatest(col1,col2)
from tbl
group by least(col1,col2),greatest(col1,col2) 但是如果只有一对(x,y)或(y,x)存在,这可能会返回表中没有的行。
要避免这种情况,请使用
select least(col1,col2) as col1,greatest(col1,col2) as col2
from tbl
group by least(col1,col2),greatest(col1,col2)
having count(*)>1
union all
select col1,col2
from tbl
where (least(col1,col2),greatest(col1,col2)) in (select least(col1,col2) as col1,greatest(col1,col2) as col2
from tbl
group by least(col1,col2),greatest(col1,col2)
having count(*)=1
) https://stackoverflow.com/questions/48938232
复制相似问题