请注意我有两张桌子:
我希望表薪水中的trnamt更新到rec记录中的tbl_emi,但金额不应超过每条记录的emi金额,例如在这种情况下,应添加工资表中的金额1000 500到第一个记录,另一个500到第二个记录到tbl_emi表
tbl_emi
EMI DUEDT REC Acno
500 4/30/2014 500 123
500 5/30/2014 0 123
500 6/30/2014 0 123
slary
Acno Trnamt
123 1000
我使用了以下查询,但它仍然在tbl_emi tbale中的rec字段+工资表中的trnamt添加,但不应超过emi数量。
select query1:为累积的emi
创建临时表select a.emi, a.duedt, a.rec, a.acno, coalesce(sum(b.emi),0) as emi_accumulated
into #accumulated_amount5
from tbl_emi a
left join tbl_emi b on a.acno = b.acno and b.duedt < a.duedt
group by a.emi, a.duedt, a.rec, a.acno;
Query2:为工资金额
创建临时表select a.*, s.RECAMT as salary_amt
into #accumulated_amount_with_salary5
from #accumulated_amount5 a
inner join Tbl_Fin s on a.acno = s.CARDNO;
更新查询1:更新重新计算金额
update #accumulated_amount_with_salary5
set rec = rec + case
when salary_amt < emi_accumulated then 0
when (salary_amt - emi_accumulated) < emi then salary_amt - emi_accumulated
else emi
end
更新Query2
update t
set lastrecdate=(CAST(GETDATE() AS DATE)), rec = a.rec
from tbl_emi t
inner join #accumulated_amount_with_salary5 a on t.acno = a.acno and t.duedt = a.duedt
--Finance
答案 0 :(得分:2)
假设您有累积和函数,通过计算累计emi
值并与trnamt
进行比较,这相对容易:
with toupdate as (
select e.*, sum(emi) over (partition by acno order by duedt) as cumemi
from tbl_emi e
)
update toupdate
set rec = (case when trnamt > cumemi then emi
else trnamt - cumemi + emi
end)
from toupdate join
slary
on toupdate.acno = slary.acno and
toupdate.cumemi - emi < trnamt;
即使没有累积总和,您仍然可以使用相关子查询执行相同的操作。
编辑:
在SQL Server 2008中,您可以将累积总和表示为:
with toupdate as (
select e.*,
(select sum(e2.emi)
from tbl_emi e2
where e2.acno = e.acno and
e2.duedt <= e.duedt
) as cumemi
from tbl_emi e
)
update toupdate
set rec = (case when trnamt > cumemi then emi
else trnamt - cumemi + emi
end)
from toupdate join
slary
on toupdate.acno = slary.acno and
toupdate.cumemi - emi < trnamt;
答案 1 :(得分:0)
你可以在工资表上插入触发器后使用,它会在工资表中的每次插入后更新tbl_emi表, 有关如何在sql-server中创建触发器的参考,请参阅http://www.codeproject.com/Articles/25600/Triggers-SQL-Server