【求助】Sum函数求和问题
已知学生成绩表:
id,数学,语文,英语
01,80,70,60
01,60,70,80
01,85,75,65
02,65,75,85
02,90, 95, 85
02,65,60,80
查询每个学好ID增加“单科成绩总和”列,如下所示增加了01和02学员所有考试的数学成绩总和
查询生成如下表
id,数学,语文,英语,数学合计
01,80,70,60, 225
01,60,70,80, 225
01,85,75,65, 225
02,65,75,85, 220
02,90, 95, 85, 220
02,65,60,80, 220
[解决办法]
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (id nvarchar(4),数学 int,语文 int,英语 int)
insert into [TB]
select '01',80,70,60 union all
select '01',60,70,80 union all
select '01',85,75,65 union all
select '02',65,75,85 union all
select '02',90,95,85 union all
select '02',65,60,80
select * from [TB]
SELECT A.* ,(SELECT SUM(数学) FROM TB WHERE id = A.id) AS 数学合计
FROM dbo.TB A
/*
id数学语文英语数学合计
01807060225
01607080225
01857565225
02657585220
02909585220
02656080220*/
if object_id('[TB]') is not null
drop table [TB]
go
create table [TB] (id nvarchar(4),数学 int,语文 int,英语 int)
insert into [TB]
select '01',80,70,60
union all
select '01',60,70,80
union all
select '01',85,75,65
union all
select '02',65,75,85
union all
select '02',90,95,85
union all
select '02',65,60,80
--sql2000
select id,数学,语文,英语,(select sum([数学]) from tb where id=a.id) 数学合计 from tb a
--sql2005以上
select id,数学,语文,英语,SUM([数学]) over(partition by id) 数学合计 from TB