I'm looking for a methodology to compare the difference between 2 rows in the same table. From what I found here (How to get difference between two rows for a column field?) it's almost what I wanted. I have done the following code:
create table #tmpTest
(
id_fund int null,
id_ShareType int null,
ValueDate datetime null,
VarNAV float null,
FundPerf float null,
)
insert into #tmpTest(id_fund, id_ShareType, ValueDate, VarNAV)
values(1,1,'20140101',100)
insert into #tmpTest(id_fund, id_ShareType, ValueDate, VarNAV)
values(1,1,'20140102',20)
update #tmpTest
set hrc.FundPerf = (isnull(hrn.VarNAV, 0) - hrc.VarNAV)/hrc.VarNAV
from #tmpTest hrc
left join #tmpTest hrn on hrn.ValueDate = (select min(ValueDate) from #tmpTest where ValueDate > hrc.ValueDate)
and hrc.id_fund = hrn.id_fund and hrc.id_ShareType = hrn.id_ShareType
My issue is that the result I'm computing starts on line 1 instead of line 2.
Hereunder the result I'm obtaining:
id_fund id_ShareType ValueDate VarNAV FundPerf
------- ------------ ------------------- ------- -----------------------------
1 1 2014-01-01 00:00:00 100 -0.8
1 1 2014-01-02 00:00:00 20 -1
whereas I'd like it to be that way:
id_fund id_ShareType ValueDate VarNAV FundPerf
------- ------------ ------------------- ------- -----------------------------
1 1 2014-01-01 00:00:00 100 -1
1 1 2014-01-02 00:00:00 20 -0.8
What's wrong with my approach?
In the blue text, you can see the calculation of the SQL delta between two rows. To calculate a difference, you need a pair of records; those two records are “the current record” and “the previous year's record”. You obtain this record using the LAG() window function.
Here's the SQL query to compare each row with previous row. In the above query, we join sales table with itself using an INNER JOIN condition g2.id=g1.id + 1 that allows you to compare each row with its previous row. Please note, this condition depends on the fact that our id column has consecutive numbers.
Select the data range you want to compare, and in the Ribbon, go to Home > Conditional Formatting > Highlight Cells Rules > Duplicate Values.
SQL Server DATEDIFF() Function The DATEDIFF() function returns the difference between two dates.
You are not restricting the minimum to the same fund and share type.
update #tmpTest
set hrc.FundPerf = (isnull(hrn.VarNAV, 0) - hrc.VarNAV)/hrc.VarNAV
from #tmpTest hrc left join
#tmpTest hrn
on hrn.ValueDate = (select min(ValueDate)
from #tmpTest tt
where tt.ValueDate > hrc.ValueDate and
hrc.id_fund = tt.id_fund and hrc.id_ShareType = tt.id_ShareType
) and
hrc.id_fund = hrn.id_fund and hrc.id_ShareType = hrn.id_ShareType ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With