2

我有一个包含材料信息的表格,其中一种材料具有从一种到多种成分。

该表如下所示:

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's 和重量百分比)的不同材料,但具有相同重量百分比的相同成分 id 可以在多种材料中。

我需要找到ID具有完全相同数量的成分、相同成分 ID 和相同重量百分比的材料(在数据示例中,材料 ID 为 1 和 3)最好有如下输出:

ID Duplicate ID's
1 1,3
2 15,25
....

只是为了澄清这个问题:我有数千种材料,如果我只获得重复行的 id 对我没有帮助 - 我想看看是否可以在同一行中获得重复材料 id 的组或领域。

4

2 回答 2

3

在包含所有成分的 CTE 中构建一个 XML 字符串,并使用该字符串来确定哪些材料是重复的。

SQL小提琴

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 |
于 2013-04-05T21:21:31.060 回答
0

那么您可以使用以下代码来获取重复值,

Select EMP_NAME as NameT,count(EMP_NAME) as DuplicateValCount   From dbo.Emp_test
group by Emp_name having count(EMP_NAME) > 1
于 2014-06-17T06:43:08.810 回答