Hi Gabe
Not sure if this is the logic you want to apply, but you may want to add join clauses for the FundID. Should improve it considerably. I have bolded the changes I made
;with Propagate as (
select
TradingDate = b.TradingDate,
SharesOutstanding = a.SharesOutstanding,
AsOfDate = b.AsOfDate,
FundID = a.FundID
from #Stocks a
inner join (
select
FundID = s2.FundID,
TradingDate = s2.TradingDate,
AsOfDate = max(s1.SharesOutstandingChangeDate)
from #Stocks s1
inner join #Stocks s2 on s1.SharesOutstandingChangeDate <= s2.TradingDate
and s1.FundID = s2.FundID
group by s2.FundID, s2.TradingDate
) b on a.TradingDate = b.AsOfDate
and a.FundID = b.FundID
)
--update s
--set SharesOutstanding = p.SharesOutstanding
select *
from #Stocks s
inner join Propagate p
on s.TradingDate = p.TradingDate
and s.FundID = p.FundID