SQL Server 横转纵 行转列

CREATE TABLE #T_A(
    d_month int
    , CompanyName varchar(200)
    ,  profits INT
) 
INSERT INTO #T_A
SELECT 1,N'公司A',123
UNION
SELECT 2,N'公司B',234
UNION
SELECT 3,N'公司C',345
UNION
SELECT 4,N'公司D',395
UNION
SELECT 5,N'公司D',678
UNION
SELECT 6,N'公司D',888
UNION
SELECT 7,N'公司D',777
UNION
SELECT 8,N'公司A',444
UNION
SELECT 9,N'公司A',342
UNION
SELECT 10,N'公司C',447
UNION
SELECT 11,N'公司D',362
UNION
SELECT 12,N'公司A',555
 
--select * from #T_A 
declare @sql varchar(max)
set @sql=''
select @sql=@sql + ',['+rtrim(CompanyName)+']=sum(case CompanyName when '''+rtrim(CompanyName)+''' then profits else 0 end)'
from #T_A group by CompanyName

exec('select d_month'+@sql+'from  #T_A group by d_month' )
DROP TABLE #T_A


SQL Server 横转纵 行转列_第1张图片



你可能感兴趣的:(技术专栏)