SELECT DATE
, DepartA=STUFF((SELECT ','+[DepartA] FROM [tb] WHERE [DATE]=a.[DATE] FOR XML PATH('')), 1, 1, '')
, DepartB=STUFF((SELECT ','+[DepartB] FROM [tb] WHERE [DATE]=a.[DATE] FOR XML PATH('')), 1, 1, '')
, DepartC=STUFF((SELECT ','+[DepartC] FROM [tb] WHERE [DATE]=a.[DATE] FOR XML PATH('')), 1, 1, '')
FROM [tb] a
GROUP BY [DATE]
你的写法有点问题,改一下就可以了。
SELECT [DATE], [DepartA]=STUFF((SELECT ','+[DepartA] FROM [tb] WHERE [DATE]=a.[DATE] FOR XML PATH('')), 1, 1, '')
, [DepartB]=STUFF((SELECT ','+[DepartB] FROM [tb] WHERE [DATE]=a.[DATE] FOR XML PATH('')), 1, 1, '')
, [DepartC]=STUFF((SELECT ','+[DepartC] FROM [tb] WHERE [DATE]=a.[DATE] FOR XML PATH('')), 1, 1, '')
FROM [tb] a
GROUP BY [DATE]
因为部门列数不确定,所以还是在SQL里完成了,动态SQL语句
set @sql3=@sql3+',['+@ColName+']=STUFF((SELECT '
set @sql3=@sql3+ ''','''+'+'
set @sql3=@sql3+' ['+@ColName+'] '+' FROM [#tab2] WHERE [DATE]=a.[DATE] FOR XML PATH('''')), 1, 1, '''') '
FETCH NEXT from @cur2 into @ColName