ms sql 行列转化
--建立测试环境
Create Table 表(year varchar(10),name varchar(10),value varchar(10))
--插入数据
insert into 表
select '2002','a','1' union
select '2002','b','4' union
select '2002','c','5' union
select '2003','a','7' union
select '2003','b','5' union
select '2003','c','4' union
select '2004','a','4'
select * from 表
--测试语句
DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT name'
SELECT @SQL= @SQL+
',sum(CASE WHEN year = ''' + year + ''' THEN value else 0 END) [' + year + ']'
FROM (SELECT DISTINCT year FROM 表) A
SET @SQL=@SQL+' FROM 表 GROUP BY name'
exec (@SQL)
--删除测试环境
Drop Table 表
/*
name 2002 2003 2004
a 1 7 4
b 4 5 0
c 5 4 0
*/
Create Table 表(year varchar(10),name varchar(10),value varchar(10))
--插入数据
insert into 表
select '2002','a','1' union
select '2002','b','4' union
select '2002','c','5' union
select '2003','a','7' union
select '2003','b','5' union
select '2003','c','4' union
select '2004','a','4'
select * from 表
--测试语句
DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT name'
SELECT @SQL= @SQL+
',sum(CASE WHEN year = ''' + year + ''' THEN value else 0 END) [' + year + ']'
FROM (SELECT DISTINCT year FROM 表) A
SET @SQL=@SQL+' FROM 表 GROUP BY name'
exec (@SQL)
--删除测试环境
Drop Table 表
/*
name 2002 2003 2004
a 1 7 4
b 4 5 0
c 5 4 0
*/