日期:2014-05-18  浏览次数:20433 次

SQL列的计算 谢谢

        A列         B列         C列       D列       E列           总数
1行
2行




求   总数=A列+B列   +C列-D列+E列的SQL语句
A列到E列都是有数据的
谢谢

------解决方案--------------------
select * from tablename where 总数=A列+B列 +C列-D列+E列

update tablename set 总数=A列+B列 +C列-D列+E列

select 总数=A列+B列 +C列-D列+E列 from tablename

不知道楼主需要的是哪种?
------解决方案--------------------
我要动态
行数不确定

语句跟行数没有关系!


--建表
create table test
(
a int,
b int,
c int,
d int,
e int,
总数 int
)
--插入数据
insert into test select 1,2,3,4,5,null
insert into test select 6,7,8,9,10,null
insert into test select 11,12,13,14,15,null
insert into test select 16,17,18,19,20,null
insert into test select 21,22,23,24,25,null
insert into test select 26,27,28,29,30,null

--查看数据
select * from test
--结果
1 2 3 4 5 NULL
6 7 8 9 10 NULL
11 12 13 14 15 NULL
16 17 18 19 20 NULL
21 22 23 24 25 NULL
26 27 28 29 30 NULL


--查询
select a,b,c,d,e,总数=A+B +C-D+E from test

--结果
1 2 3 4 5 7
6 7 8 9 10 22
11 12 13 14 15 37
16 17 18 19 20 52
21 22 23 24 25 67
26 27 28 29 30 82

--更新总数
update test set 总数=A+B +C-D+E

--再查询
select * from test
--结果
1 2 3 4 5 7
6 7 8 9 10 22
11 12 13 14 15 37
16 17 18 19 20 52
21 22 23 24 25 67
26 27 28 29 30 82

------解决方案--------------------
交叉制表--检查列的计数值和长度并加入行数据(9)
除了需要证实列的计数值和名称长度,如果一切正常用户还需要填写#rownames表
--check column count
if (select count(*) from #colnames)> 1023
begin
drop table #colnames
raiserror 51004 'distinct column count exceeded max of 1023 '
return -1
end
--verify colnames do not exceed max length
if (select max(datalength(rtrim(colname))-1) from #colnames)> 29
begin
drop table #colnames
raiserror 51050 'column data length exceeded max of 30 '
return -1
end
--if all is ok ,continue to add #rownames data
select @chvexec= 'insert #rownames select distinct '+
case @introwtype
when 1 then 'convert(varchar(255), ' else ' '
end +rtrim(@chrrowhead)+
case @introwtype
when 1 then ') '
else ' '
end + 'from '+@chrsource
--print @chvexec
exec(@chvexec) //在网上找的 你看你能不能用