ListSQL在SQLSERVER中
我正在尝试在SQLServer中聚合一个“STRING”字段。 我想在Oracle中find与LISTAGG相同的函数。
你知道如何做同样的function或另一种方法吗?
例如,
Field A | Field B 1 | A 1 | B 2 | A
我希望这个查询的结果是
1 | AB 2 | A
在SQL Server中,您可以使用FOR XML PATH
来获得结果:
select distinct t1.FieldA, STUFF((SELECT distinct '' + t2.FieldB from yourtable t2 where t1.FieldA = t2.FieldA FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,0,'') data from yourtable t1;
看演示与SQL小提琴
在Sqlserver中:
SELECT FieldA , STUFF(( SELECT ','+ FieldB FROM TableName a WHERE b.FieldA = a.FieldA FOR XML PATH('')),1 ,1, '') Members FROM TableName b GROUP BY FieldA;
在Mysql中:
SELECT FieldA, GROUP_CONCAT(FieldB) AS Members FROM TableName GROUP BY FieldA ORDER BY FieldA;
在Oracle中:
SELECT FieldA, LISTAGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldA) AS Members FROM TableName GROUP BY FieldA;
在SQL Server 2017中添加STRING_AGG :
SELECT t.name,STRING_AGG (c.name, ',') AS csv FROM sys.tables t JOIN sys.columns c on t.object_id = c.object_id GROUP BY t.name ORDER BY 1
而且,对于相反的情况, STRING_SPLIT是有用的,并且在SQL Server 2016中可用