DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT @s = @s + ',' + QUOTENAME(CodeDetail) + '=max(case when [CodeDetail]='
+ QUOTENAME(CodeDetail, '''') + ' then [CodeDetail] else ''0'' end)'
FROM table1
GROUP BY LocationCode
EXEC('select [LocationCode]'+@s+' from table1 group by [LocationCode]')
------其他解决方案-------------------- declare @F varchar(max),@str varchar(max)
select @F=STUFF((select ','+quotename(codedetail) from #table3 for XML path('')),1,1,'')
set @str='select * from TB pivot(max(Tallydata) for codedetail in ('+ @F +')) as X'
exec(@str) ------其他解决方案--------------------
SELECT a.LocationCode ,
STUFF(( SELECT ',' + CodeDetail
FROM table1 b
WHERE b.LocationCode = a.LocationCode
FOR
XML PATH('')
), 1, 1, '') 'CodeDetail'
FROM table1 a
GROUP BY LocationCode
select top 1
STUFF(
(
SELECT (case CodeDetail when '' then '' else (CodeDetail + ',') end) FROM WLRS_Locational_Detail where locationcode=@locationcode
FOR XML PATH('')
),1,0,'') CodeDetail
from WLRS_Locational_Detail T