日期:2014-05-17 浏览次数:20566 次
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 数学 语文 英语 数学合计
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
--sql2000
select id,数学,语文,英语,(select sum([数学]) from tb where id=a.id) 数学合计 from tb a
--sql2005以上
select id,数学,语文,英语,SUM([数学]) over(partition by id) 数学合计 from TB