这里是一个工作的例子 - 见注释进行说明:
--First set up your data in a temp table
declare @oidcid table (Oid int, Cid char(1));
insert into @oidcid values
(1,'a'),
(1,'b'),
(2,'f'),
(3,'c'),
(4,'f'),
(5,'a'),
(5,'b'),
(6,'f'),
(6,'g'),
(7,'f');
--This cte gets a table with all of the cids in order, for each oid
with cte as (
select distinct Oid, (select Cid + ',' from @oidcid i2
where i2.Oid = i.Oid order by Cid
for xml path('')) Cids
from @oidcid i
)
select Oid, cte.Cids
from cte
inner join (
-- Here we get just the lists of cids that appear more than once
select Cids, Count(Oid) as OidCount
from cte group by Cids
having Count(Oid) > 1) as gcte on cte.Cids = gcte.Cids
-- And when we list them, we are showing the oids with duplicate cids next to each other
Order by cte.Cids
请注意,这是一对匹配,我需要做的不是个人字母匹配。因此,在所需的结果集中,对于Oid = 2,它不应包含Oid 6的字母匹配。因为它也具有字母'G'。希望这将清除 – hss