I want to calculate the opening/closing amount of the month on the condition. I am using calculative columns for the same. In My case, the closing of prev month is the Opening for the next month, so I try to use the LAG function. but not able to achieve results.
In the first month the OpeningAmt will be YearAmt
My Table structure is as Follows
| emp_code | year1 | year2 | col_code | paidin | YearAmt | Increment | Used |
|---|---|---|---|---|---|---|---|
| 330 | 202204 | 202303 | a3 | 202204 | 15000.00 | 1250.00 | 100 |
| 330 | 202204 | 202303 | a3 | 202205 | 15000.00 | 1250.00 | 100 |
| 330 | 202204 | 202303 | a3 | 202206 | 15000.00 | 1250.00 | 100 |
| 330 | 202204 | 202303 | a3 | 202207 | 15000.00 | 1250.00 | 100 |
| 330 | 202204 | 202303 | a3 | 202208 | 15000.00 | 1250.00 | 100 |
and my expected output as follows
| emp_code | year1 | year2 | col_code | paidin | YearAmt | Increment | Used | OpeningAmt | ClosingAmt |
|---|---|---|---|---|---|---|---|---|---|
| 330 | 202204 | 202303 | a3 | 202204 | 15000.00 | 1250.00 | 100 | 15000.00 | 16150.00 |
| 330 | 202204 | 202303 | a3 | 202205 | 15000.00 | 1250.00 | 100 | 16150.00 | 17300.00 |
| 330 | 202204 | 202303 | a3 | 202206 | 15000.00 | 1250.00 | 100 | 17300.00 | 18450.00 |
| 330 | 202204 | 202303 | a3 | 202207 | 15000.00 | 1250.00 | 100 | 18450.00 | 19600.00 |
| 330 | 202204 | 202303 | a3 | 202208 | 15000.00 | 1250.00 | 100 | 19600.00 | 20750.00 |
Attempted Query:
SELECT *,
CASE WHEN year1 = MonthYear THEN NULL ELSE
LAG(StartMonthClosing,1) OVER (ORDER BY emp_code, col_code, MonthYear)
END OtherMonthOpening
FROM (
SELECT emp_code, year1,year2,col_code, MonthYear ,YearAmt, Increment, Used,
CASE WHEN year1 = MySalaryTable.paidin THEN YearAmt ELSE NULL END StartMonthOpening,
CASE WHEN year1 = MySalaryTable.paidin THEN YearAmt + Increment - Used ELSE NULL END StartMonthClosing
FROM MyreimTable
INNER JOIN MySalaryTable ON MyreimTable.emp_code = MySalaryTable.emp_code
)
AS P2