我有一个只包含两列的表,比如Name,DepartmentId如下
CREATE TABLE #TempDepartment
(
Name NVARCHAR(50)
,DepartmentId INT
)
INSERT INTO #TempDepartment VALUES
('ABC',1)
,('ABC2',1)
,('DEF',2)
,('XYZ',3)
我希望以逗号分隔格式检索不同departmentId的列表。我怎样才能在SQL中实现这一点?基本上没有共同的组项,因此与使用STUFF或COALESCE混淆。
预期产出为 - 1,2,3
答案 0 :(得分:3)
尝试此查询
Select Top 1 STUFF((SELECT ', ' + CAST(DepartmentId AS Varchar(20))
FROM #TempDepartment b Group By DepartmentId
FOR XML PATH('')), 1, 2, '') CSV
From #TempDepartment
<强> Fiddle Output 强>
O / P:
+---------+
| CSV |
+---------|
| 1, 2, 3 |
+---------+
答案 1 :(得分:2)
试试这个:
;WITH CTE AS
(
SELECT DISTINCT DepartmentId
FROM #TempDepartment
)
SELECT TOP (1)
STUFF((SELECT ',' + CAST(DepartmentId AS VARCHAR(10))
FROM CTE FOR XML PATH('')), 1, 1, '')
FROM CTE
应该产生所需的输出:
1,2,3