--> 测试数据: [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
select sum(case when 算法 = '加' then 数值 else - 数值 end) from tb
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 行)*/
select sum(case when 算法 = '加' then 数值 else 0-数值 end) from tb
--> 测试数据: [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
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 行)*/