34,590
社区成员
发帖
与我相关
我的任务
分享
WITH a1 (姓名,朋友) AS
(
SELECT '张三','李四' UNION ALL
SELECT '张三','王五' UNION ALL
SELECT '李四','张三' UNION ALL
SELECT '王五','张三' UNION ALL
SELECT '刘黑七','王八'
)
SELECT *
FROM a1 a
WHERE NOT EXISTS(SELECT * FROM a1 b where a.朋友=b.姓名 AND a.姓名<>b.朋友)
--drop table test
--go
create table test(姓名 varchar(10), 朋友 varchar(10))
insert into test
select '张三' ,'李四' union all
select '张三' ,'王五' union all
select '李四' ,'张三' union all
select '王五' ,'张三' union all
select '刘黑七' ,'王八'
go
;with t
as
(
select 姓名 ,朋友,
ROW_NUMBER() over(order by getdate()) rownum
from test t1
),
tt
as
(
select *,
(select count(*) from t t2
where t1.姓名 = t2.朋友 and t1.朋友 = t2.姓名
and t1.rownum >= t2.rownum) as flag
from t t1
)
select 姓名 ,朋友
from tt
where flag = 0
/*
姓名 朋友
张三 李四
张三 王五
刘黑七 王八
*/