I have two tables CustomerStatementSetup
in which data is maintained that this customer has entered financials for 2 years or 3 years or so on. Another table is CustomerStatementSetup
which has all the information against a year and a coacoade; the user has entered this value.
CustomerStatementSetup
:
CSSCode CustomerCode FinancialYear CreatedOn
-------------------------------------------------
80349 42151 2019 Date
80350 42151 2020 //
71131 42120 2018 //
71132 42120 2017 //
CustomerStatement
:
CSTCode CSSCODE COACode COAValue CustomerCode
-------------------------------------------------------
1 80349 10700 50 42151
2 80349 10701 20 42151
3 80350 10700 15 42151
4 80350 10701 45 42151
5 71131 10700 20 42120
6 71131 10701 25 42120
7 71132 10700 150 42120
8 71132 10701 200 42120
I want to get the current and previous COAValue against a customercode and COAcode and then perform some calculations on it so it returns only the calculated value against that customer.
E.g.: Against CustomerCode 42151 two financials have been performed, 2020 and 2019. Against 2020 there are two entries in customerstatementsetup against coacode. I want to calculate a column like ((Current Year Value -last Year Value)/Last Year Value)*100 against customercode=42151 and coacode=10700
. So it will be ((15-50)/50)*100
My sample query is this but this is not returning the required result.
-- perform calculation against current and previous
select csst.CSSCode,csst.FinancialYear,S.COACode,S.COAValue
from CustomerStatementSetup csst
left join CustomerStatement S on S.CSSCode = csst.CSSCode
-- get coavalue against customercode and coacode
left outer join (
select top 1 cst.COAValue,css.CSSCode from CustomerStatementSetup css
left join CustomerStatement cst on cst.CSSCode =css.CSSCode
where cst.CustomerCode=42151 cst.COACode=10700 ORDER BY css.financialyear DESC
) C1
on C1.CSSCode =csst.CSSCode
-- get previous value against customercode and coacode
left outer join (
select * from (
select row_number() OVER (ORDER BY css.FinancialYear desc) as rowNo, cst.COAValue,css.CSSCode
from CustomerStatementSetup css
inner join CustomerStatement cst on cst.CSSCode =css.CSSCode
where cst.CustomerCode = 42151 and cst.COACode=10700
) as tbl
where tbl.rowNo = 2
) P1
on P1.CSSCode =csst.CSSCode
I am having trouble understanding the full outer join.
I want to get the current year and previous yearin the same row so I can further use this for my formula. My sample result:
CustomerCode COACode CurrentYearValue PreviousYearValue
--------------------------------------------------------------
42151 10700 15 50