Given the following table:
+--------------------+-----------+
| Account | Company |
+--------------------+-----------+
| gloria.harding | FB |
| gloria.harding | Twitter |
| bryant.schuman | Google |
| jerry.maxwell | Apple |
| rachel.heptinstall | FB |
| rachel.heptinstall | Twitter |
| rachel.heptinstall | Instagram |
+--------------------+-----------+
I want to group the result by Account but I need the Company column of each row in the group to be concatenated and display all of them in an anonymous column like so:
+--------------------+------------------------+
| Account | 'Companies' |
+--------------------+------------------------+
| gloria.harding | FB, Twitter |
| bryant.schuman | Google |
| jerry.maxwell | Apple |
| rachel.heptinstall | FB, Twitter, Instagram |
+--------------------+------------------------+
Is this possible to achieve on TSQL?
The first requirement can easily be achieved by grouping the Account column but I don't know how to achieve the latter.
You can use the following - using stuff()
select distinct Account,
STUFF((Select ','+Company
from tablename T1
where T1.account=T2.account
FOR XML PATH('')),1,1,'') from tablename T2
There is an easier solution than working with XML for someone who is using SQL Server 2017 and above. Microsoft introduced STRING_AGG
command and this fits perfectly into what you want.
SELECT DISTINCT Account, (SELECT STRING_AGG(Company, ',')
FROM TableName T1
WHERE T1.Account = T2.Account)
FROM TableName T2;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.