id    数值      算法
1      10     加
2      20     减
3      15     加
4      10     加
5      25     减
对“数值”字段进行求累计值,结果:10-20+15+10-25,根据算法字段给出的值对数值字段的值进行累加或累减。

解决方案 »

  1.   


    --> 测试数据: [ta]
    if object_id('[ta]') is not null drop table [ta]
    create table [ta] (id int,数值 int,算法 varchar(2))
    insert into [ta]
    select 1,10,'加' union all
    select 2,20,'减' union all
    select 3,15,'加' union all
    select 4,10,'加' union all
    select 5,25,'减'declare @sql varchar(8000)
    set @sql='select '
    select @sql=@sql+case 算法 when '加' then '+' else '-' end +ltrim(数值)from [ta]
    exec(@sql)
    --结果:
    -10
      

  2.   

    select sum(case when 算法 = '加' then 数值 else - 数值 end) from tb
      

  3.   

    create table [ta] (id int,数值 int,算法 varchar(2))
    insert into [ta]
    select 1,10,'加' union all
    select 2,20,'减' union all
    select 3,15,'加' union all
    select 4,10,'加' union all
    select 5,25,'减'select sum(case when 算法 = '加' then 数值 else - 数值 end) from tadrop table ta/*            
    ----------- 
    -10(所影响的行数为 1 行)*/
      

  4.   

    select sum(case when 算法 = '加' then 数值 else 0-数值 end) from tb