I have a following table in which I have employee's transactions having salary as Code 'S' in it:
Id | Code | Amount | Date
1 | B | 40 | 2017-01-01
1 | S | 45000 | 2017-01-02
1 | D | 30000 | 2017-01-15
1 | B | 15000 | 2017-01-20
1 | S | 45000 | 2017-02-02
1 | B | -20000 | 2017-02-04
1 | B | -10000 | 2017-02-05
My objective is to see how many days does it take for the employee to drain all his salary
Here is the output I want:
Id | Code | Amount | Month | # days when all salary drains
1 | S | 45000 | 01 | 20
1 | S | 45000 | 01 | 0
I have followed this and tried following SQL query:
with cte as
(
select *,
--CASE WHEN Transaction_Code in ('521', '522') then Transaction_Amt else null end as Last_V_ID
-- find the latest 'V' ID per ArtNo
max(case when Transaction_Code in ('521', '522') then Transaction_Amt end)
over (partition by INTERNAL_ACCT_NUM order by value_date) as Last_V_ID
from [10.16.42.25].[Cross_Sell_PL].[dbo].[PL_NONPL_TRANS]
WHERE INTERNAL_ACCT_NUM = '0103PBS8T6001'
--order by value_date
)
select *,
case when Transaction_Code in ('521', '522') then Transaction_Amt else
( lag(Last_V_ID,1,0) OVER (PARTITION BY INTERNAL_ACCT_NUM ORDER BY VALUE_DATE) )
+ Transaction_Amt end as running_balance,
sum(case when Transaction_Amt < Last_V_ID then null else Transaction_Amt end)
over (partition by INTERNAL_ACCT_NUM order by VALUE_DATE rows unbounded preceding)
from cte
order by Internal_Acct_num, value_date
The problem is I am not able to restrict the calculation between the code and also unable to calculate days.