--2:动态拼接行转列
DECLARE @sql VARCHAR(8000)
SET @sql = 'SELECT CompanyID,'
SELECT @sql = @sql + 'SUM(CASE Name WHEN '''+[Name]+''' THEN [TypeID] ELSE 0 END) AS '''+QUOTENAME(Name)+''','
FROM (SELECT DISTINCT Name FROM [dbo].[BD_Warehouse]) AS a
SELECT @sql = LEFT(@sql,LEN(@sql)-1) + ' FROM [dbo].[BD_Warehouse] GROUP BY CompanyID'
PRINT(@sql)
EXEC(@sql)
GO