create table dupt(cat varchar(10), num int)
insert dupt(cat,num) values ('A',1),('A',2),('A',3),
('B',1),('B',2),
('C',1),('C',2), ('C',3),
('D',1),('D',2), ('D',4),
('E',1),('E',2),
('F',1),('F',2)
我需要创建一个查找重复数据的报告。从上面的示例数据中,报告需要显示cat A的数据由cat C复制(注意num值和记录的数量),cat B由cat E和F复制。显示该数据的最佳方式是什么?
示例输出
-------------
|cat | dupby|
-------------
| A | C |
| B | E, F |
-------------
答案 0 :(得分:1)
更新:仅使用common table expression和stuff()
with select ... for xml path ('')
method of string concatenation切换到传统的集合匹配,仅用于最终结果:
;with cte as (
select *
, cnt = count(*) over (partition by cat)
from t
)
, duplicates as (
select
x.cat
, dup_cat = x2.cat
from cte as x
inner join cte as x2
on x.cat < x2.cat
and x.num = x2.num
and x.cnt = x2.cnt
group by x.cat, x2.cat, x.cnt
having count(*) = x.cnt
)
select
d.cat
, dupby = stuff((
select ', '+i.dup_cat
from duplicates i
where i.cat = d.cat
for xml path (''), type).value('.','varchar(8000)')
,1,2,'')
from duplicates d
where not exists (
select 1
from duplicates i
where d.cat = i.dup_cat
)
group by d.cat
rextester演示:http://rextester.com/KHAG98718
返回:
+-----+-------+
| cat | dupby |
+-----+-------+
| A | C |
| B | E, F |
+-----+-------+