SQLSERVER中的ListAGG我试图在SQLSERVER中聚合一个“String”字段。我想找到与Oracle相同的LISTAGG函数。您知道如何执行相同的功能或其他方法吗?例如,Field A | Field B1 | A1 | B2 | A我希望这个查询的结果是1 | AB2 | A
3 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
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,'') datafrom yourtable t1;
跃然一笑
TA贡献1826条经验 获得超6个赞
MySQL
SELECT FieldA , GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ',') AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;
Oracle&DB2
SELECT FieldA , LISTAGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;
PostgreSQL
SELECT FieldA , STRING_AGG(FieldB, ',' ORDER BY FieldB) AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;
SQLServer
SQLServer≥2017&Azure SQL
SELECT FieldA , STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;
WITH CTE_TableName AS ( SELECT FieldA, FieldB FROM TableName)SELECT t0.FieldA , STUFF(( SELECT ',' + t1.FieldB FROM CTE_TableName t1 WHERE t1.FieldA = t0.FieldA ORDER BY t1.FieldB FOR XML PATH('')), 1, LEN(','), '') AS FieldBs FROM CTE_TableName t0 GROUP BY t0.FieldA ORDER BY FieldA;
SQLite
排序需要CTE或子查询
WITH CTE_TableName AS ( SELECT FieldA, FieldB FROM TableName ORDER BY FieldA, FieldB)SELECT FieldA , GROUP_CONCAT(FieldB, ',') AS FieldBs FROM CTE_TableName GROUP BY FieldA ORDER BY FieldA;
不订货
SELECT FieldA , GROUP_CONCAT(FieldB, ',') AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;
添加回答
举报
0/150
提交
取消