gpt4 book ai didi

sql-server - T-SQL 是否有用于连接字符串的聚合函数?

转载 作者:行者123 更新时间:2023-12-01 17:17:42 24 4
gpt4 key购买 nike

Possible Duplicates:
Implode type function in SQL Server 2000?
Concatenate row values T-SQL

我正在查询一个如下所示的 View :

BuildingName    PollNumber
------------ ----------
Foo Centre 12
Foo Centre 13
Foo Centre 14
Bar Hall 15
Bar Hall 16
Baz School 17

我需要编写一个查询,将 BuildingName 分组在一起并显示 PollNumber 列表,如下所示:

BuildingName    PollNumbers
------------ -----------
Foo Centre 12, 13, 14
Bar Hall 15, 16
Baz School 17

如何在 T-SQL 中执行此操作?我宁愿不为此编写存储过程,因为这看起来有点过分,但我不完全是数据库人员。似乎我需要像 SUM() 或 AVG() 这样的聚合函数,但我不知道 T-SQL 是否有这样的函数。我使用的是 SQL Server 2005。

最佳答案

适用于 SQL Server 2017 及更高版本:

STRING_AGG()

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

SELECT
HeaderValue, STRING_AGG(ChildValue,', ')
FROM @YourTable
GROUP BY HeaderValue

输出:

HeaderValue 
----------- -------------
1 CCC
2 B<&>B, AAA
3 <br>, A & Z

(3 rows affected)

对于 SQL Server 2005 及 2016 年之前的版本,您需要执行以下操作:

--Concatenation with FOR XML and eleminating control/encoded character expansion "& < >"
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

输出:

HeaderValue ChildValues
----------- -------------------
1 CCC
2 AAA, B<&>B
3 <br>, A & Z

(3 row(s) affected)

另外,请注意,并非所有 FOR XML PATH 连接都能像上面的示例那样正确处理 XML 特殊字符。

关于sql-server - T-SQL 是否有用于连接字符串的聚合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5031204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com