我有2个表hrPft
,其中包含cEmp
列和dpft
列。列hradv
,列iAdv
,cEmp
,dAmnt
。该表的数据如下所示
表hrPft
cEmp dpft
1001 300.000
1002 1000.000
表格hradv
iAdv cEmp dAmnt
1 1001 100.000
2 1001 50.000
3 1001 200.000
4 1001 10.000
1 1002 200.000
2 1002 500.000
3 1002 100.000
4 1002 100.000
我的任务是按以下方式显示数据
cEmp dpft dAmnt
1001 300 100
1001 200(dpft-aAmnt) 50
1001 150 200
1001 0(should display 0 when goes -ve) 50
1001 0 60(50+10)
答案 0 :(得分:1)
这会产生接近您想要的结果集的东西。你可能不得不玩一些比较(交换<
和<=
等)以获得正确的行为(你没有指定)减法时减去{ {1}}正好为0。
我也暂不评论此代码可能有效或无效的效率。
dpft
(另请注意,我如何提供您的示例数据 - 通过将其写为表变量和declare @hrpft table (cEmp int not null,dpft decimal(19,3) not null)
insert into @hrpft(cEmp,dpft) values
(1001,300.000 ),
(1002,1000.000)
declare @hradv table (iAdv int not null, cEmp int not null,dAmnt decimal(19,3) not null)
insert into @hradv(iAdv,cEmp,dAmnt) values
(1,1001,100.000 ),
(2,1001,50.000 ),
(3,1001,200.000 ),
(4,1001,10.000 ),
(1,1002,200.000 ),
(2,1002,500.000 ),
(3,1002,100.000 ),
(4,1002,100.000 )
select
p.cEmp,
p.dpft - COALESCE((select SUM(dAmnt) from @hradv a2 where a2.cEmp = p.cEmp and a2.iAdv < a.iAdv),0),
a.dAmnt,
a.iAdv
from
@hrpft p
inner join
@hradv a
on
p.cEmp = a.cEmp
where p.dpft - COALESCE((select SUM(dAmnt) from @hradv a2 where a2.cEmp = p.cEmp and a2.iAdv < a.iAdv),0) >= 0
union all
select
p.cEmp,
0,
COALESCE((select SUM(dAmnt) from @hradv a2 where a2.cEmp = p.cEmp and a2.iAdv <= a.iAdv),0) - p.dpft,
a.iAdv
from
@hrpft p
inner join
@hradv a
on
p.cEmp = a.cEmp
where p.dpft - COALESCE((select SUM(dAmnt) from @hradv a2 where a2.cEmp = p.cEmp and a2.iAdv <= a.iAdv),0) < 0
order by
cEmp,iAdv
语句,任何人都可以立即将其复制并粘贴到SSMS中并开始处理数据 - 您可能会考虑使用类似的方式来呈现您的样本数据以用于将来的任何问题。)
结果:
INSERT