22,302
社区成员




if object_id('[tb]') is not null drop table [tb]
go
create TABLE tb(
[id] [int] NOT NULL,--主键
[studentid] [int] NULL,--学生id
[classid] [int] NULL,--课程id
[year] [int] NULL,--年份
[xueyuanid] [nvarchar](10) NULL,--学院id
[value] [float] NULL --分数
)
insert tb select 11,'2','3','2008','1','33'
insert tb select 12,'2','3','2007','1','33'
insert tb select 13,3,3,'2007','1','33'
insert tb select 14,3,4,'2006','1','33'
insert tb select 15,4,4,'2006','1','33'
insert tb select 16,4,4,'2006','1','33'
insert tb select 17,5,5,'2005','1','33'
insert tb select 18,5,6,'2005','1','33'
insert tb select 19,6,5,'2005','1','33'
insert tb select 20,7,6,'2009','1','33'
insert tb select 21,7,6,'2010','1','33'
go
--select * from tb
declare @s varchar(8000)
set @s='select studentid '
select @s=@s+',sum(case when [year]='+ltrim([year])+' and classid='+ltrim(classid)+' and xueyuanid='+ltrim(xueyuanid)
+' then [value] else 0 end) ['+ltrim([year])+'年-课程'+ltrim(classid)+'-学院'+ltrim(xueyuanid)+']'
from tb
group by [year],classid,xueyuanid
order by [year],classid,xueyuanid
select @s=@s+' from tb group by studentid'
exec(@s)
/*
studentid 2005年-课程5-学院1 2005年-课程6-学院1 2006年-课程4-学院1 2007年-课程3-学院1 2008年-课程3-学院1 2009年-课程6-学院1 2010年-课程6-学院1
----------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ----------------------
2 0 0 0 33 33 0 0
3 0 0 33 33 0 0 0
4 0 0 66 0 0 0 0
5 33 33 0 0 0 0 0
6 33 0 0 0 0 0 0
7 0 0 0 0 0 33 33
(6 行受影响)
*/