sql - JOIN two table to themselves and calculate a value based on the two -


using sql server 2012

i have 2 tables joined.

[apxfirm].[advapp].[vmarketindexrate]  [apxfirm].[advapp].[vmarketindex] 

joining these 2 able indexname, asofdate , rate

however want calculate weighted sum of 2 indexes. s&p500 weighted .4 , dj average weighted .6. tried query below , result not blended rate. first indexes rate.

for example if on given date sp = 100 , dj = 200 blend rate should 40 + 120 = 160

here query

use apxfirm select 'blend' 'indexname', ir1.asofdate,    sum(ir1.rate*.4+ir2.rate*.6) 'blendrate'   [apxfirm].[advapp].[vmarketindexrate] ir1    inner join [apxfirm].[advapp].[vmarketindex] mi1     on ir1.indexid = mi1.indexid      inner join [apxfirm].[advapp].[vmarketindexrate] ir2     on ir2.indexid = ir1.indexid , ir2.asofdate = ir1.asofdate     inner join [apxfirm].[advapp].[vmarketindex] mi2     on ir2.indexid = ir1.indexid , ir2.asofdate = ir1.asofdate   mi1.indexname = 'sp'   ,  mi2.indexname = 'djind'   group mi1.indexname ,            ir1.asofdate ,            ir1.rate ,            mi2.indexname ,            ir2.asofdate ,            ir2.rate 

here sample of data. note weight not actual column. included illustrative purposes.

indexname   asofdate    rate    weight  indexname   asofdate    rate    weight  blendrate sp500   12/31/2012      100        0.6  dowjones    12/31/2012  90      0.4     96 sp500   1/31/2013       110        0.6  dowjones    1/31/2013   95      0.4     104 sp500   2/28/2013       120        0.6  dowjones    2/28/2013   100     0.4     112 sp500   3/31/2013       130        0.6  dowjones    3/31/2013   110     0.4     122 

here desired output.

indexname   asofdate    blendrate blend   12/31/2012      96 blend   1/31/2013       104 blend   2/28/2013       112 blend   3/31/2013       122 

if understood problem right, problem in "from" block - try use next one:

select 'blend' 'indexname'       ,ir1.asofdate       ,sum(ir1.rate*.4+ir2.rate*.6) 'blendrate'  [apxfirm].[advapp].[vmarketindexrate] ir1      inner join [apxfirm].[advapp].[vmarketindex] mi1              on ir1.indexid = mi1.indexid       inner join [apxfirm].[advapp].[vmarketindexrate] ir2              on ir2.asofdate = ir1.asofdate      inner join [apxfirm].[advapp].[vmarketindex] mi2              on ir2.indexid = mi2.indexid  mi1.indexname = 'sp'   , mi2.indexname = 'djind'  group mi1.indexname         ,ir1.asofdate         ,ir1.rate         ,mi2.indexname         ,ir2.asofdate         ,ir2.rate 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -