2013-04-05 74 views
1

我有一張材料信息表,其中一個材料具有一個到多個構成要素。在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組中的同一行或字段。

回答

2

在包含所有組分的CTE中構建一個XML字符串,並使用該字符串找出哪些材料是重複的。

SQL Fiddle

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 

Results

| ID | MATERIALIDS | 
-------------------- 
| 1 |   1,3 | 
+0

的Mikael,謝謝。結果得到的結果是組分id與相關的重量百分比和它們使用的材料。 我需要幾乎相反的結果 - 一個表格,將有2列:1 - 行號(ID),2 - 逗號分隔相同的材料ID的(即有相同的成分和相同的重量百分比爲他們每個人) – user2250303 2013-04-05 23:11:08

+0

@ user2250303好的,我想我知道你在這裏想要什麼。你想找到與它們中的組件完全相同的材料嗎?就像找到所有相同的食譜來烘焙蛋糕,蛋糕的方式我認爲是一樣的材料我的你的世界和組成部分是成分。 – 2013-04-06 04:57:50

+1

+1(over by 1/0) – 2013-04-06 07:00:54

0

那麼你可以使用下面的代碼,以獲得重複的值,

Select EMP_NAME as NameT,count(EMP_NAME) as DuplicateValCount From dbo.Emp_test 
group by Emp_name having count(EMP_NAME) > 1