如何获取重复名称的所有 ID 并将其传递给 table
How to get all the ID's of Duplicate Name and pass it to table
以下是我的数据。 ProductId 和 Name 是字符串数据类型
ProductId Name
"101" John
"201" Marry
"301" Marry
"401" John
"501" John
我需要识别重复的名称并检索他们的 ProductId,并最终像下面那样附加这些 ID structure.These 结果将在 DataTable(c#) 中。
ProductId Name
"101,401,501" John`
"201,301" Marry
请告诉我如何实现的解决方案。
这是 STUFF
的方法
create table #MyTable(ProductId int, [Name] varchar(16))
insert into #MyTable
values
(101,'John'),
(201,'Marry'),
(301,'Marry'),
(401,'John'),
(501,'John')
select distinct
t.[Name]
,ProductId = STUFF((
SELECT ',' + cast(t2.ProductId as char(3))
FROM #MyTable t2
WHERE t.[Name] = t2.[Name]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from
#MyTable t
drop table #MyTable
以下是我的数据。 ProductId 和 Name 是字符串数据类型
ProductId Name
"101" John
"201" Marry
"301" Marry
"401" John
"501" John
我需要识别重复的名称并检索他们的 ProductId,并最终像下面那样附加这些 ID structure.These 结果将在 DataTable(c#) 中。
ProductId Name
"101,401,501" John`
"201,301" Marry
请告诉我如何实现的解决方案。
这是 STUFF
create table #MyTable(ProductId int, [Name] varchar(16))
insert into #MyTable
values
(101,'John'),
(201,'Marry'),
(301,'Marry'),
(401,'John'),
(501,'John')
select distinct
t.[Name]
,ProductId = STUFF((
SELECT ',' + cast(t2.ProductId as char(3))
FROM #MyTable t2
WHERE t.[Name] = t2.[Name]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from
#MyTable t
drop table #MyTable