SQL Server 行列转换 sql语句
面试题:怎么把这样一个表儿
year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4
查成这样一个结果
year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4
create table t
(
year varchar(4),
month varchar(1),
amount int
)
insert t values('1991','1',1)
insert t values('1991','2',2)
insert t values('1991','3',3)
insert t values('1991','4',4)
insert t values('1992','1',5)
insert t values('1992','2',6)
insert t values('1992','3',7)
insert t values('1992','4',8)
--SQL SERVER 2000 静态SQL,指课程只有1、2、3、4这四个月份。(以下同)
select year ,
max(case month when '1' then amount else 0 end) m1,
max(case month when '2' then amount else 0 end) m2,
max(case month when '3' then amount else 0 end) m3,
max(case month when '4' then amount else 0 end) m4
from t
group by year
--SQL SERVER 2000 动态SQL,指课程不止1、2、3、4这四个月份。(以下同)
declare @sql varchar(8000)
set @sql = 'select year '
select @sql = @sql + ' , max(case month when ''' + month + ''' then amount else 0 end) [' + month + ']'
from (select distinct month from t) as a
set @sql = @sql + ' from t group by year'
exec(@sql)