如何连接每个组的某个列中的所有字符串 [英] How to concatenate all strings from a certain column for each group
本文介绍了如何连接每个组的某个列中的所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这个表 [Table1]
Suppose I have this table [Table1]
Name Mark
------- ------
ABC 10
DEF 10
GHI 10
JKL 20
MNO 20
PQR 30
我的 SQL 语句应该是什么来检索如下所示的记录:(按[标记]分组).我已经完成了 1 和 2 列,但不知道如何完成第三列(将 [name] 与相同的 [mark] 连接起来)
What should be my SQL statement to retrieve a record that looks like this: (group by [mark]). I have done the 1 and 2 columns but don't know how to accomplish the third column (concat the [name] with the same [mark])
mark count names
---- ----- -----------
10 3 ABC,DEF,GHI
20 2 JKL,MNO
30 1 PQR
我正在使用 Microsoft SQL.请帮忙.谢谢
I'm using Microsoft SQL. Please help. Thanks
推荐答案
如果是 MS SQL 2005 或更高版本.
If MS SQL 2005 or higher.
declare @t table([name] varchar(max), mark int)
insert @t values ('ABC', 10), ('DEF', 10), ('GHI', 10),
('JKL', 20), ('MNO', 20), ('PQR', 30)
select t.mark, COUNT(*) [count]
,STUFF((
select ',' + [name]
from @t t1
where t1.mark = t.mark
for xml path(''), type
).value('.', 'varchar(max)'), 1, 1, '') [values]
from @t t
group by t.mark
<小时>
输出:
mark count values
----------- ----------- --------------
10 3 ABC,DEF,GHI
20 2 JKL,MNO
30 1 PQR
这篇关于如何连接每个组的某个列中的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文