sql 服务器累积差异

sql server cumulative diff

我有 2 个 table 即 hrPft 有列 cEmpdpft。和 Table hradviAdvcEmpdAmnt。 table 的数据如下所示

Table hrPft

cEmp           dpft
1001        300.000
1002        1000.000

Table 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)

这会生成接近您想要的结果集的结果。当减法减少 dpft 精确到 0.

我暂时也不会评论此代码的效率如何。

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

(另请注意,我是如何呈现您的示例数据的 - 通过将其编写为 table 变量和 INSERT 语句,任何人都可以立即将其复制并粘贴到 SSMS 中并开始使用数据 - 您可能需要考虑使用类似的方式来呈现样本数据以应对未来的任何问题)。

结果:

cEmp                      dAmnt       iAdv
----------- ------------- ----------- -----------
1001        300.000       100.000     1
1001        200.000       50.000      2
1001        150.000       200.000     3
1001        0.000         50.000      3
1001        0.000         60.000      4
1002        1000.000      200.000     1
1002        800.000       500.000     2
1002        300.000       100.000     3
1002        200.000       100.000     4