列转行SQL语句(列数不确定)
如下图所示,求SQL语句
------解决方案--------------------参考 :
create table cjb(姓名 char (10),课程名 char (10),成绩 [decimal](12, 2))
insert into cjb
select '张','数据库', 78 union
select '张','信息管理',80 union
select '张','专业英语',89 union
select '李','数据库' ,90 union
select '李','信息管理',67 union
select '李','专业英语',56
--方法一(SQL SERVER2005以上)
declare @groupField varchar(1000)
select @groupField=isnull(@groupField,'')+case when isnull(@groupField,'')='' then '' else ',' end+QUOTENAME(课程名)
from (select distinct rtrim(课程名) as 课程名 from cjb)t
declare @sql nvarchar(4000)
set @sql=N'select *
from
(select 姓名, rtrim(课程名) as 课程名,sum(成绩) as 成绩
from cjb
group by 姓名,rtrim(课程名)
) as x
pivot (sum(成绩)for 课程名 in ('+@groupField+')) as pvt
order by 姓名'
EXEC (@sql)
--方法二(一般用在SQL SERVER2000)
declare @sql varchar(8000)
set @sql=''
select @sql=@sql + ',['+rtrim(课程名)+']=max(case rtrim(课程名) when '''+rtrim(课程名)+''' then 成绩 end)'
from cjb group by rtrim(课程名)
exec('select 姓名'+@sql+' from cjb group by 姓名')
drop table cjb
------解决方案--------------------create table cjb(姓名 char (10),课程名 char (10),成绩 [decimal](12, 2))
insert into cjb
select '张','数据库', 78 union
select '张','信息管理',80 union
select '张','专业英语',89 union
select '李','数据库' ,90 union
select '李','信息管理',67 union
select '李','专业英语',56
--方法一(SQL SERVER2005以上)
declare @groupField varchar(1000)
select @groupField=isnull(@groupField,'')+case when isnull(@groupField,'')='' then '' else ',' end+QUOTENAME(课程名)
from (select distinct rtrim(课程名) as 课程名 from cjb)t