with cte as (
select row_number() over (partition by vcl.crew_ipn order by vcl.account_period desc, vcl.wage_start_date desc) as rn, vcl.ACCOUNT_PERIOD, vcl.CREW_IPN, ca.* from bhr.BASS_CREW_ACCOUNTBALANCE ca, bhr.PN_VCREW_LIST vcl
where vcl.ACCOUNT_PERIOD between '201901' and '201905'
and vcl.ACCPERIOD_ITEMID = ca.ACCPERIOD_ITEMID
and vcl.ACTIVITY_ID = ca.ACTIVITY_ID
), cte2 as (
select row_number() over (partition by vcl.crew_ipn order by vcl.account_period desc, vcl.wage_start_date desc) as rn, vcl.ACCOUNT_PERIOD, vcl.CREW_IPN, ca.* from bhr.BASS_CREW_ACCOUNTBALANCE ca, bhr.PN_VCREW_LIST vcl
where vcl.ACCOUNT_PERIOD between '201901' and '201905'
and vcl.ACCPERIOD_ITEMID = ca.ACCPERIOD_ITEMID
and vcl.ACTIVITY_ID = ca.ACTIVITY_ID
)

select cte.CREW_IPN, cte.ACCOUNT_PERIOD, cte.CREW_OPENAMOUNT, cte.CREW_CLOSEAMOUNT, cte.CREW_TRANSFERAMOUNT, cte2.ACCOUNT_PERIOD, cte2.CREW_OPENAMOUNT, cte2.CREW_CLOSEAMOUNT, cte2.CREW_TRANSFERAMOUNT from cte, cte2
where cte.CREW_ITEM_ID = cte2.CREW_ITEM_ID
and cte2.rn = cte.rn +1
and cte.CREW_OPENAMOUNT != (case when cte.ACCOUNT_PERIOD = cte2.ACCOUNT_PERIOD then cte2.CREW_TRANSFERAMOUNT else cte2.CREW_CLOSEAMOUNT end)
order by 1
