比如工资表
id sal hours days operator
1 200 2 3 +,*
2 250 3 4 *,-
3 350 2 5 -,/
operator 为列 sal 和hours,days 的运算顺序,
如id = 1, 为 (200+2)*3
id=2, 为 250*3-4
id=3, 为 (350-2)/5
如何用sql 计算每行的值?
谢谢!
------解决方案--------------------
WITH a1 (id,sal,HOURS,DAYS,operator) AS
(
select 1, 200, 2, 3,'+,*' UNION ALL
select 2, 250, 3, 4,'*,-' UNION ALL
select 3, 350, 2, 5,'-,/'
)
,a2 AS
(
select
CASE
WHEN LEFT(operator,1)='+' THEN (sal+HOURS)
WHEN LEFT(operator,1)='-' THEN (sal-HOURS)
WHEN LEFT(operator,1)='*' THEN (sal*HOURS)
WHEN LEFT(operator,1)='/' THEN (sal/HOURS)
END result,DAYS,operator
FROM a1
)
select
CASE
WHEN right(operator,1)='+' THEN (result+DAYS)
WHEN right(operator,1)='-' THEN (result-DAYS)
WHEN right(operator,1)='*' THEN (result*DAYS)
WHEN right(operator,1)='/' THEN (result/DAYS)
END result
FROM a2
------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
go
create table #temp( [id] varchar(100), [sal] int, [hours] int, [days] int, [operator] varchar(100));
insert #temp
select '1','200','2','3','+,*' union all
select '2','250','3','4','*,-' union all
select '3','350','2','5','-,/'
--SQL:
SELECT
id, sal, [hours], [days], operator,
result = CAST(
CASE RIGHT(operator, 1)