[英]Summarize the list into a comma-separated string
This is the current result that can be changed from day to day 这是当前可以每天更改的结果
(int) (nvarchar)
Number Grade
--------------
1 a
1 c
2 a
2 b
2 c
3 b
3 a
What I need help is to achieve this result below. 我需要帮助的是在下面实现这个结果。
Number Grade
-----------------
1 a, c
2 a, b, c
3 b, a
Use: 采用:
declare @t table(Number int, Grade varchar)
insert @t values(1, 'a'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'),
(3, 'b'), (3, 'a')
select t1.Number
, stuff((
select ',' + Grade
from @t t2
where t2.Number = t1.Number
for xml path(''), type
).value('.', 'varchar(max)'), 1, 1, '') [values]
from @t t1
group by t1.Number
Obviously you'll need to replace dbo.tablename
with your actual table. 显然你需要用你的实际表替换
dbo.tablename
。 Also I'm assuming you're using SQL Server 2005 or better - always useful to specify. 此外,我假设你使用的是SQL Server 2005或更好 - 总是有用的指定。
SELECT Number, Grades = STUFF((
SELECT ', ' + Grade FROM dbo.tablename
WHERE Number = x.Number
FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '')
FROM dbo.tablename AS x
GROUP BY Number;
In SQL Server 2017 and Azure SQL Database, you can use the new aggregation function STRING_AGG()
, which is a lot tidier in this case: 在SQL Server 2017和Azure SQL数据库中,您可以使用新的聚合函数
STRING_AGG()
,在这种情况下,它更加整洁:
SELECT Number, Grades = STRING_AGG(Grade,',')
FROM dbo.tablename
GROUP BY Number;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.