列转行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
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 u01
(医案编号 varchar(5),药物编号 varchar(5))
insert into u01
select '01','01' union all
select '01','02' union all
select '01','03' union all
select '02','07' union all
select '02','08' union all
select '03','06' union all
select '04','01' union all
select '04','02' union all
select '04','03' union all
select '04','04' union all
select '04','05' union all
select '05','09' union all
select '05','08'
declare @tsql varchar(6000),@c1 varchar(1000),@c2 varchar(1000)
select @c1=isnull(@c1+',','')+'isnull(['+rtrim(number)+'],'''') ''药物'+rtrim(number)+''' ',
@c2=isnull(@c2+',','')+'['+rtrim(number)+']'
from master.dbo.spt_values
where type='P' and number>=1 and number<=
(select max(c) from (select count(1) 'c' from u01 group by 医案编号) t)
select @tsql='select 医案编号,'+@c1+'
from (select 医案编号,药物编号,
row_number() over(partition by 医案编号 order by getdate()) ''rn''
from u01) t
pivot(max(药物编号) for rn in ('+@c2+')) p '
exec(@tsql)
/*
医案编号 药物1 药物2 药物3 药物4 药物5
----- ----- ----- ----- ----- -----
01 01 02 03
02 07 08
03 06
04 01 02 03 04 05
05 09 08
(5 row(s) affected)
*/