|
endmancan achieve all the results,
if exists(select 1 from sysobjects where id = object_id(N't1'))
drop table t1
go
create table t1
(sno varchar(10),
sname varchar(10)
)
if exists(select 1 from sysobjects where id = object_id(N't2'))
drop table t2
go
create table t2
(cno varchar(10),
cname varchar(10)
)
if exists(select 1 from sysobjects where id = object_id(N't3'))
drop table t3
go
create table t3
(sno varchar(10),
cno varchar(10),
grade int
)
insert into t1 values('201601','Zhang San')
insert into t1 values('201602','Li Si')
insert into t2 values('1','Chinese')
insert into t2 values('2','Math')
insert into t2 values('3','English')
insert into t3 values('201601','1',100)
insert into t3 values('201601','2',80)
insert into t3 values('201601','3',120)
insert into t3 values('201601','1',111)
insert into t3 values('201601','2',90)
insert into t3 values('201601','3',124)
go
--Execute query
declare @sql varchar(2000)
set @sql ='select t1.sno,t1.sname '
select @SQl = @sql +',sum(case t3.cno when'+ t2.cno + 'then t3.grade else 0 end)' + t2.cname
from t2
set @Sql = @sql + 'from t1, t3 where t1.sno = t3.sno group by t1.sno,t1.sname'
exec( @sql)
Got as follows
sno sname language mathematics english
201601 Zhang San 211 170 244
But what I want is:
sno sname language mathematics english
201601 Zhang San 100 80 120
201602 Li Si 111 90 124 |
|