92

我正在尝试在 SQLServer 中聚合一个“字符串”字段。我想在 Oracle 中找到相同的函数 LISTAGG 。

您知道如何执行相同的功能或另一种方法吗?

例如,

Field A | Field B
1       |  A
1       |  B
2       |  A

我希望这个查询的结果是

1 | AB
2 | A
4

4 回答 4

171

MySQL

SELECT FieldA
     , GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ',') AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

甲骨文和 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;

SQL 服务器

SQL Server ≥ 2017 & Azure SQL

SELECT FieldA
     , STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

SQL Server ≤ 2016(包括 CTE 以鼓励DRY 原则

  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;
于 2013-10-13T18:27:29.617 回答
94

SQL Server 2017开始,该STRING_AGG功能可用,大大简化了逻辑:

select FieldA, string_agg(FieldB, '') as data
from yourtable
group by FieldA

请参阅带有演示的 SQL Fiddle

在 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 Fiddle

于 2013-03-18T13:18:54.880 回答
20

在 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 中可用

于 2017-01-05T15:30:42.507 回答
2

这可能对某人也有用..

即用于数据分析师和数据分析类型的目的..(即不分组)..

在 SQL*Server 2017 String_agg 函数存在之前..

(即只返回一行..)

select distinct
SUBSTRING (
stuff(( select distinct ',' + [FieldB] from tablename order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') 
,1,0,'' ) 
,2,9999)
from 
    tablename 

例如返回逗号分隔值 A,B

于 2019-01-31T01:21:21.890 回答