Hi everyone
I want to create new opening balance column based on min key_id and new closing balance column based on max key_id.
Original dataset
|cust_num|key_id|Opening Balance|Closing Balance|
|1|544684|5516.01|-223.99|
|1|548139|-223.99|-181.67|
|1|548141|-181.67|-181.67|
|1|548143|-181.67|-50.52|
|1|550954|-50.52|-50.52|
The desired result should be as follows:
cust_num | key_id | Opening Balance | Closing Balance | Opening Balance_new | Closing Balance_new |
---|---|---|---|---|---|
1 | 544684 | 5516.01 | -223.99 | 5516.01 | 0 |
1 | 548139 | -223.99 | -181.67 | 0 | 0 |
1 | 548141 | -181.67 | -181.67 | 0 | 0 |
1 | 548143 | -181.67 | -50.52 | 0 | 0 |
1 | 550954 | -50.52 | -50.52 | -50.52 |
How would I write the SQL query?
Here is how I wrote it and I'm not getting correct results:
SELECT prod_inst_id AS cust_num
,key_id
,repay_start_balance AS 'Opening Balance'
,repay_end_balance AS 'Closing Balance'
,(
SELECT repay_start_balance
FROM fin_prod_inst_repay_Sched WITH (NOLOCK)
WHERE start_date >= '2024-02-01'
AND start_date <= '2024-02-29'
AND key_id = (
SELECT min(key_id)
FROM fin_prod_inst_repay_Sched WITH (NOLOCK)
WHERE start_date >= '2024-02-01'
AND start_date <= '2024-02-29'
)
) 'Opening Balance_new'
,(
SELECT repay_end_balance
FROM fin_prod_inst_repay_Sched WITH (NOLOCK)
WHERE start_date >= '2024-02-01'
AND start_date <= '2024-02-29'
AND key_id = (
SELECT max(key_id)
FROM fin_prod_inst_repay_Sched WITH (NOLOCK)
WHERE start_date >= '2024-02-01'
AND start_date <= '2024-02-29'
)
) 'Closing Balance_new'
FROM fin_prod_inst_repay_Sched WITH (NOLOCK)
WHERE start_date >= '2024-02-01'
AND start_date <= '2024-02-29'
GROUP BY prod_inst_id
,key_id
,repay_start_balance
,repay_end_balance
ORDER BY prod_inst_id
Thanks in advance
M