need to group records based on matching reversals

南楼画角 提交于 2020-03-04 18:44:00

问题


This question is continuation to my earlier post.

Need to group records based on matching reversal in sql

I will be more clear with one complex example from my transaction table.

Row_Number  LOAN_ID TXN_ENTRY_API_NAME          TXN_AMT
        1   100     ReverseSpreadPayment        2250
        2   100     SpreadPayment               -2250
        3   100     ReverseSpreadPayment        2250
        4   100     SpreadPayment               -2250
        5   100     ReverseSpreadPayment        2250
        6   100     SpreadPayment               -2250
        7   100     ReverseSpreadPayment        2250
        8   100     ReverseSpreadPayment        2250
        9   100     SpreadPayment               1000

In the above example

rownumber 1&2 are matched records bcoz payment has an associated reverse payment, hence sum these two. rownumber 3&4 are matched records bcoz payment has an associated reverse payment, hence sum these two. rownumber 5&6 are matched records bcoz payment has an associated reverse payment, hence sum these two. rownumber 7 does not have an associated matching payment amount, hence is ophan. Keep it as it is. rownumber 8 does not have an associated matching payment amount, hence is ophan. Keep it as it is. rownumber 9 does not have an associated matching reverse payment amount, hence is ophan. Keep it as it is.

To understand you better i just added row_number column here, where as in my transaction table we dont have any row_number column.

My expected output should be like below table.

                    LOAN_ID     TXN_ENTRY_API_NAME                 TXN_AMT
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment                2250
                        100     ReverseSpreadPayment                2250
                        100     SpreadPayment                       1000

What I am expecting to generate row number function like below so that i can group by using row number column.

The Row number is an ordering column which is generated by me, thats it.


回答1:


I think this is just row_number() and aggregation:

select listagg(row_number, ',') within group (order by row_number) as row_numbers,
       loan_id, txn_entry_api_name, sum(txn_amt) as txn_amt,
       listagg(txn_entry_api_name, ',') within group (order by row_number) as txn_entry_api_name
from (select t.*,
             row_number() over (partition by loan_id, txn_entry_api_name, abs(txn_amt) order by row_number) as seqnum
      from t
     ) t
group by seqnum;


来源:https://stackoverflow.com/questions/60287312/need-to-group-records-based-on-matching-reversals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!