- 爱易网页
-
MSSQL教程
- 与表中每条记录进行计算,怎样写速度最快!解决方案
日期:2014-05-18 浏览次数:20548 次
与表中每条记录进行计算,怎样写速度最快!
A表结构:
字段 ID A1 A2 A3 A4 A5
内容 1 26.936 0.5387 0.0128 0.5241 162.403
2 13.382 0.2676 0.0231 0.3139 85.234
3 27.377 0.5475 0.0537 0.3055 79.979
... ... ... ... ... ...
有一组数据:18.101, 0.325, 0.0246, 0.3731,96.128 分别与A表中所有记录的A1~A5
字段数值进行计算,例如:
26.936-18.101, 0.5387-0.325, 0.0128-0.0246, 0.5241-0.3055, 162.403- 96.128
怎样写,计算速度最快!
------解决方案--------------------
declare @a table(ID int, A1 numeric(10,3), A2 numeric(10,3), A3 numeric(10,3), A4 numeric(10,3), A5 numeric(10,3))
insert @a select 1 ,26.936, 0.5387, 0.0128, 0.5241, 162.403
union all select 2,13.382, 0.2676, 0.0231, 0.3139, 85.234
union all select 3,27.377, 0.5475 ,0.0537, 0.3055 ,79.979
select id,a1-b1,a2-b2,a3-b3,a4-b4,a5-b5 from @a A,(select 18.101 b1, 0.325 b2, 0.0246 b3,0.3731 b4,96.128 b5) B
------解决方案--------------------
declare @ta table(ID int,A1 decimal(10,3),A2 decimal(10,3),A3 decimal(10,3),A4 decimal(10,3),A5 decimal(10,3))
insert @ta
select 1, 26.936, 0.5387, 0.0128, 0.5241, 162.403 union all
select 2, 13.382, 0.2676, 0.0231, 0.3139, 85.234 union all
select 3, 27.377, 0.5475, 0.0537, 0.3055, 79.979
----把值写到表中
declare @tb table(A1 decimal(10,3),A2 decimal(10,3),A3 decimal(10,3),A4 decimal(10,3),A5 decimal(10,3))
insert @tb select 18.101,0.325,0.0246,0.3731,96.128
----运算
select
A1 = a.A1 - b.A1,
A2 = a.A2 - b.A2,
A3 = a.A3 - b.A3,
A4 = a.A4 - b.A4,
A5 = a.A5 - b.A5
from @ta as a ,@tb as b
/*结果
A1 A2 A3 A4 A5
------------- ------------- ------------- ------------- -------
8.835 .214 -.012 .151 66.275
-4.719 -.057 -.002 -.059 -10.894
9.276 .223 .029 -.067 -16.149
*/