|
楼主 |
发表于 2020-7-6 16:15:01
|
显示全部楼层
endman 可以实现的把全部成绩加起来,
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','张三')
insert into t1 values('201602','李四')
insert into t2 values('1','语文')
insert into t2 values('2','数学')
insert into t2 values('3','英语')
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
--执行查询
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)
得到如下
sno sname 语文 数学 英语
201601 张三 211 170 244
可我要的应是:
sno sname 语文 数学 英语
201601 张三 100 80 120
201602 李四 111 90 124
|
|