sqlserver的listagg
时间: 2023-10-15 18:02:51 浏览: 149
SQL Server 并没有内置的 `LISTAGG` 函数,但可以使用其他方法来实现类似的功能。以下是几种常见的方法:
1. 使用 `FOR XML PATH`:
```sql
SELECT
Column1,
STUFF(
(SELECT ',' + Column2
FROM YourTable
WHERE Column1 = t.Column1
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS List
FROM YourTable AS t
GROUP BY Column1;
```
2. 使用递归 CTE:
```sql
WITH CTE AS (
SELECT
Column1,
Column2,
ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY Column2) AS rn,
COUNT(*) OVER (PARTITION BY Column1) AS cnt
FROM YourTable
)
,RecursiveCTE AS (
SELECT
Column1,
CAST(Column2 AS NVARCHAR(MAX)) AS List,
rn,
cnt
FROM CTE
WHERE rn = 1
UNION ALL
SELECT
c.Column1,
CAST(rc.List + ',' + c.Column2 AS NVARCHAR(MAX)),
c.rn,
c.cnt
FROM CTE AS c
INNER JOIN RecursiveCTE AS rc ON c.Column1 = rc.Column1 AND c.rn = rc.rn + 1
)
SELECT
Column1,
MAX(List) AS List
FROM RecursiveCTE
WHERE rn = cnt
GROUP BY Column1;
```
这些方法可以将每个分组内的多个值合并为一个逗号分隔的字符串。请将 `YourTable` 替换为你要操作的表名,`Column1` 和 `Column2` 替换为相应的列名。
阅读全文