我在SQL Server 2008中有一个像这样的表:
Id Name
------------
1 Jack
2 John
3 Maria
4 Jack
5 Jack
6 John
我试图在一列中看到所有具有相同名称的ID。
select Count(Id), Name
from myTable
group by Name
上面的查询给出了具有相同名称的ID数。但我希望看到的是:
Id Name
------------
1,4,5 Jack
2,6 John
3 Maria
我该如何提供?感谢
答案 0 :(得分:2)
Declare @YourTable table (ID int, Name varchar(50))
Insert Into @YourTable values
(1,'Jack'),
(2,'John'),
(3,'Maria'),
(4,'Jack'),
(5,'Jack'),
(6,'John')
Select Name
,IDs = Stuff((Select Distinct ','+cast(ID as varchar(25))
From @YourTable
Where Name=A.Name
For XML Path ('')),1,1,'')
From (Select Distinct Name From @YourTable ) A
返回
Name IDs
Jack 1,4,5
John 2,6
Maria 3