我有桌子: 用户A, 用户B, numberOfConnections
我想写一个查询,它只返回没有反向意义的行或示例: 对于数据:
1 2 10
1 3 10
1 5 10
1 6 10
2 6 10
2 5 10
5 1 10
5 2 10
3 1 10
它应该返回
1 2 10
1 3 10
1 5 10
1 6 10
2 6 10
2 5 10
行:
5 1 10
5 2 10
3 1 10
无效,因为已经有相应的
1 5 10
2 5 10
3 1 10
感谢您的帮助 再见
答案 0 :(得分:2)
这将做你想要的事情
SELECT mt1.UserA, mt1.UserB, mt1.numberOfConnections
FROM MyTable mt1
LEFT OUTER JOIN MyTable mt2 ON mt1.UserA = mt2.UserB
AND mt1.UserB = mt2.UserA
WHERE mt2.UserA IS NULL
OR mt1.UserA < mt2.UserA
答案 1 :(得分:0)
为什么不添加UserA&lt; UserB在where子句中。 ?
答案 2 :(得分:0)
with t1 as (
select col1 ,col2,
row_number()
over(partition by case when col1>col2 then col1+col2 else col2+col1 end
order by case when col1>col2 then col1+col2 else col2+col1 end) as rownum
from table_1 )
select * from t1 where rownum =1
如果您的数据类型col1和col2不是varchar
,只需cast
他们
您可以将row_number
替换为group by
答案 3 :(得分:0)
使用更新
A-结果无反向
Select UserA, UserB, numberOfConnections
From TName
Where ID Not IN(
SELECT t1.ID
FROM TName As t1 INNER JOIN TName As t2 ON (t1.UserA = t2.UserB) AND (t1.UserB = t2.UserA))
B-结果反向仅重复
Select UserA, UserB, numberOfConnections
From TName
Where ID IN(
SELECT t1.ID
FROM TName As t1 INNER JOIN TName As t2 ON (t1.UserA = t2.UserB) AND (t1.UserB = t2.UserA))
C-结果仅反转不重复
Select UserA, UserB, numberOfConnections
From TName
Where ID IN(
SELECT t1.ID
FROM TName As t1 INNER JOIN TName As t2 ON (t1.UserA = t2.UserB) AND (t1.UserB = t2.UserA) and (t1.UserA<t1.UserB))
D-结果无反向且不重复反向
一个 联盟 ç