如何获取上个月和本月的累计总数?

How to get cumulative total for previous month and upto this month?

ID  pcID    contractor  approver    claimed
-------------------------------------------
1   1       one          1000         900
2   1       two          200          100
3   1       three        1000        1000
4   1       six          100          11
5   2       six          100          22
6   3       six          120           1
7   4       three        102          10

从上面table,我需要得到这个月和上个月的累计金额,审批人和索赔以及当月审批人,索赔金额基于承包商。喜欢下面 table.

ID  contractor  approver    claimed  uptothisMTApprover   uptothisMTClaimed  previousMTApprover previousMTClaimed 
-----------------------------------------------------------------------------------------------------------------
1    one          1000       900     1000                 900                0                   0
2    two          200        100     200                  100                0                   0
3    three        102        10      1102                 1010               1000                1000
4    six          120        1       320                  34                 200                 33

提前致谢..

您似乎想要每个 contractor 的最新行,如 pcID 所定义,以及之前所有月份的累计总和。

您可以使用 window 函数:

select contractor, approver, claimed, 
    total_approver            as uptothisMTApprover, 
    total_claimed             as uptothisMTClaimed,
    total_approver - approver as previousMTApprover, 
    total_claimed  - claimed  as previousMTClaimed
from (
    select t.*,
        row_number()  over(partition by contractor order by pcID desc) rn,
        sum(approver) over(partition by contractor) total_approver,
        sum(claimed)  over(partition by contractor) total_claimed
    from mytable t
) t
where rn = 1