我在SQL Server中有以下表格
Names TypeID
-------------
JJ 23
KK 20
LL 15
JJ 13
KK 18
JJ 10
我希望我的选择查询的结果显示如下
Names TypeID
---------------
JJ 23,13,10
KK 20,18
LL 15
我怎样才能做到这一点?请帮忙,我是sql的新手
答案 0 :(得分:2)
之前已多次回答过这个问题。例如:Does T-SQL have an aggregate function to concatenate strings?
一个好的代码片段是这样的:
set nocount on;
declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))
insert into @YourTable VALUES (1,1,'CCC')
insert into @YourTable VALUES (2,2,'B<&>B')
insert into @YourTable VALUES (3,2,'AAA')
insert into @YourTable VALUES (4,3,'<br>')
insert into @YourTable VALUES (5,3,'A & Z')
set nocount off
SELECT
t1.HeaderValue
,STUFF(
(SELECT
', ' + t2.ChildValue
FROM @YourTable t2
WHERE t1.HeaderValue=t2.HeaderValue
ORDER BY t2.ChildValue
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS ChildValues
FROM @YourTable t1
GROUP BY t1.HeaderValue
此代码取自我发布链接的同一主题。
答案 1 :(得分:1)
drop table #t
create table #t(names varchar(10),type1 int)
insert into #t values('JJ',23),
('KK',20),
('LL',15),
('JJ',13),
('KK',18),
('JJ',10)
select distinct names,stuff((select ',' +cast(type1 as varchar(10)) from #t t2 where t2.names=t1.names for xml path('') ),1,1,'') as TypeID
from #t t1
答案 2 :(得分:0)
试试这个: -
SELECT Names, GROUP_CONCAT(TypeID)
FROM YOUR_TABLE
GROUP BY Names;
答案 3 :(得分:0)
试试这个
SELECT Names, TypeID =
STUFF((SELECT ', ' + Convert(nvarchar(2),TypeID)
FROM your_table b
WHERE b.Names = a.Names
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY Names
答案 4 :(得分:-1)
试试这段代码
SELECT name, GROUP_CONCAT(typeid)
FROM test
GROUP BY name