如何使用 Stuff 压缩 SQL 行?

How to Condense SQL Rows Using Stuff?

我有一个 table 的数据,如下所示:

#测试

RecordID Name hasSpanishVersion Type TypeID
1 Test One Yes FormType1 1
1 Test One Yes FormType2 2
3 Test Three No null null
4 Test Four Yes FormType3 3
5 Test Five Yes FormType3 3

我还有一个 table 看起来像:

#formTypes

TypeID FormType
1 FormType1
2 FormType2
3 FormType3

我想做的是压缩类型列,其中有类似的记录 ID/名称。如果“hasSpanishVersion”为空,则后面两列也为空。

我希望示例 table 看起来像:

RecordID Name hasSpanishVersion Type
1 Test One Yes FormType1, FormType2
3 Test Three null null
4 Test Four Yes FormType3
5 Test Five Yes FormType3

我已经尝试了以下代码,但这只采用了所有的 FormTypes 并将它们压缩为三种不同的类型:

SELECT 
   *,
   STUFF((SELECT '; ' + t.formTypeSpanish 
          FROM #test t
          WHERE t.TypeID = ft.TypeID
          FOR XML PATH('')), 1, 1, '') as FormTypes
FROM #formTypes ft
GROUP BY ft.TypeID, ft.FormType
ORDER BY 1

您可以让您的分组列放入 Where 相关子查询中,然后将值连接到 SELECT

SELECT 
   RecordID, Name,hasSpanishVersion,
   STUFF((SELECT ',' + tt.[Type] 
          FROM formTypes tt
          WHERE 
          tt.RecordID = t1.RecordID AND 
          tt.Name = t1.Name AND
          tt.hasSpanishVersion = t1.hasSpanishVersion
          FOR XML PATH('')), 1, 1, '') as FormTypes
FROM formTypes t1
GROUP BY RecordID, Name,hasSpanishVersion
ORDER BY 1

如果您的sql-server支持STRING_AGG,还有另一种简单的方法。

SELECT RecordID, Name,hasSpanishVersion,STRING_AGG([Type] ,',') 
FROM formTypes
GROUP BY RecordID, Name,hasSpanishVersion

sqlfiddle