如何连接分组行的所有列数据?
how to concat all column data of a grouped row?
给出以下 table:
+--------------------+-----------+
| Account | Company |
+--------------------+-----------+
| gloria.harding | FB |
| gloria.harding | Twitter |
| bryant.schuman | Google |
| jerry.maxwell | Apple |
| rachel.heptinstall | FB |
| rachel.heptinstall | Twitter |
| rachel.heptinstall | Instagram |
+--------------------+-----------+
我想按 Account 对结果进行分组,但我需要将组中每一行的 Company 列连接起来并显示所有这些都在一个匿名专栏中,如下所示:
+--------------------+------------------------+
| Account | 'Companies' |
+--------------------+------------------------+
| gloria.harding | FB, Twitter |
| bryant.schuman | Google |
| jerry.maxwell | Apple |
| rachel.heptinstall | FB, Twitter, Instagram |
+--------------------+------------------------+
这可以在 TSQL 上实现吗?
第一个要求可以通过分组 Account 列轻松实现,但我不知道如何实现后者。
您可以使用以下 - 使用 stuff()
select distinct Account,
STUFF((Select ','+Company
from tablename T1
where T1.account=T2.account
FOR XML PATH('')),1,1,'') from tablename T2
对于使用 SQL Server 2017 及更高版本的人来说,有一个比使用 XML 更简单的解决方案。 Microsoft 引入了 STRING_AGG
命令,这完全符合您的要求。
SELECT DISTINCT Account, (SELECT STRING_AGG(Company, ',')
FROM TableName T1
WHERE T1.Account = T2.Account)
FROM TableName T2;
给出以下 table:
+--------------------+-----------+
| Account | Company |
+--------------------+-----------+
| gloria.harding | FB |
| gloria.harding | Twitter |
| bryant.schuman | Google |
| jerry.maxwell | Apple |
| rachel.heptinstall | FB |
| rachel.heptinstall | Twitter |
| rachel.heptinstall | Instagram |
+--------------------+-----------+
我想按 Account 对结果进行分组,但我需要将组中每一行的 Company 列连接起来并显示所有这些都在一个匿名专栏中,如下所示:
+--------------------+------------------------+
| Account | 'Companies' |
+--------------------+------------------------+
| gloria.harding | FB, Twitter |
| bryant.schuman | Google |
| jerry.maxwell | Apple |
| rachel.heptinstall | FB, Twitter, Instagram |
+--------------------+------------------------+
这可以在 TSQL 上实现吗?
第一个要求可以通过分组 Account 列轻松实现,但我不知道如何实现后者。
您可以使用以下 - 使用 stuff()
select distinct Account,
STUFF((Select ','+Company
from tablename T1
where T1.account=T2.account
FOR XML PATH('')),1,1,'') from tablename T2
对于使用 SQL Server 2017 及更高版本的人来说,有一个比使用 XML 更简单的解决方案。 Microsoft 引入了 STRING_AGG
命令,这完全符合您的要求。
SELECT DISTINCT Account, (SELECT STRING_AGG(Company, ',')
FROM TableName T1
WHERE T1.Account = T2.Account)
FROM TableName T2;