sql - 在 SQL Server 中查找重复的行组

标签 sql sql-server group-by duplicates

我有一张包含 Material 信息的表格,其中一种 Material 具有一种到多种成分。

表格如下所示:

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 和重量百分比)的不同 Material ID,但也可以使用具有相同成分的相同成分 ID重量百分比可以是多种 Material 。

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

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

只是为了澄清这个问题:我有几千种 Material ,如果我只得到重复行的 id,它不会对我有帮助 - 我想看看是否可以获取重复 Material id 的组同一行或同一字段。

最佳答案

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

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 |

关于sql - 在 SQL Server 中查找重复的行组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15841515/

相关文章:

php - 获取最后一个插入 id sqlsrv

mysql - group by中带数据函数的query如何优化

sql - 从每组的第一行和最后一行获取值

mysql - 多重连接

sql - 子选择查询中的表别名范围

sql-server - 如何在 SQL-Server 中创建一个只能访问一张表并且只能插入行的用户

html - sp_send_dbmail 在正文中嵌入 mhtml 文件

带有日期比较的mysql查询

mysql - 计算并选择 MySQL 中特定字段的所有日期

sql - int 不是一种类型