在SQL Server中查找重复的行组
问题描述:
我有一张材料信息表,其中一个材料具有一个到多个构成要素。在SQL Server中查找重复的行组
表看起来像这样:
material_id contstiuent_id constituent_wt_pct
1 1 10.5
1 2 89.5
2 1 10.5
2 5 15.5
2 7 74
3 1 10.5
3 2 89.5
一般来说,我可以具有不同的材料ID
的具有相同的成分(均ID
的和重量百分比),但也具有相同的相同的构成的id重量百分比可以在多种材料中。
我需要找到材料ID
的成分数量完全相同,成分相同且重量百分比相同(在材料ID 1和3的数据示例中) 最好的是有像输出:
ID Duplicate ID's
1 1,3
2 15,25
....
只是为了澄清这个问题:我有几千种材料,如果我只是得到重复行的id,我不会帮助我 - 我想看看是否有可能获得重复材料ID组中的同一行或字段。
答
在包含所有组分的CTE中构建一个XML字符串,并使用该字符串找出哪些材料是重复的。
MS SQL Server 2008的架构设置:
create table Materials
(
material_id int,
constituent_id int,
constituent_wt_pct decimal(10, 2)
);
insert into Materials values
(1, 1, 10.5),
(1, 2, 89.5),
(2, 1, 10.5),
(2, 5, 15.5),
(2, 7, 74),
(3, 1, 10.5),
(3, 2, 89.5);
查询1:
with C as
(
select M1.material_id,
(
select M2.constituent_id as I,
M2.constituent_wt_pct as P
from Materials as M2
where M1.material_id = M2.material_id
order by M2.constituent_id,
M2.material_id
for xml path('')
) as constituents
from Materials as M1
group by M1.material_id
)
select row_number() over(order by 1/0) as ID,
stuff((
select ','+cast(C2.material_id as varchar(10))
from C as C2
where C1.constituents = C2.constituents
for xml path('')
), 1, 1, '') as MaterialIDs
from C as C1
group by C1.constituents
having count(*) > 1
| ID | MATERIALIDS |
--------------------
| 1 | 1,3 |
答
那么你可以使用下面的代码,以获得重复的值,
Select EMP_NAME as NameT,count(EMP_NAME) as DuplicateValCount From dbo.Emp_test
group by Emp_name having count(EMP_NAME) > 1
的Mikael,谢谢。结果得到的结果是组分id与相关的重量百分比和它们使用的材料。 我需要几乎相反的结果 - 一个表格,将有2列:1 - 行号(ID),2 - 逗号分隔相同的材料ID的(即有相同的成分和相同的重量百分比为他们每个人) – user2250303 2013-04-05 23:11:08
@ user2250303好的,我想我知道你在这里想要什么。你想找到与它们中的组件完全相同的材料吗?就像找到所有相同的食谱来烘焙蛋糕,蛋糕的方式我认为是一样的材料我的你的世界和组成部分是成分。 – 2013-04-06 04:57:50
+1(over by 1/0) – 2013-04-06 07:00:54