在 SQL 中创建递归查询

Creating a recursive query in SQL

我有这样的数据:

我想查看 SQL 服务器(A、B、C、...)和(B、D、E、...)中的组的结果

我试过寻找递归但没有实现它。

我需要在 SQL 中执行此操作。

感谢您的帮助。

不用递归cte也能实现。使用 string_aggconcat 尝试以下操作。这是 demo.

select
  concat(columnA, ', ', string_agg(columnB, ', ')) as columnC
from myTable
group by
  columnA

输出:

|columnC|
*-------*
|A, B, C|
|B, D, E|

在 SQL Server 2012 中,您可以使用 XML PATH 如下

select
  concat(
  columnA, ',',
  stuff((
            select ', ' + columnB
            from myTable m1
            where m1.columnA = m2.columnA
            for xml path('')
        ), 1, 1, ''
    )) as columnC
from myTable m2
group by
  columnA