I have a query where I create 2 temp tables at the start, then I query an existing table in my DB and join this table to a subquery, and then lastly join to 1 of the temp tables. When i do this I get an error that the key I'm joining on from the existing table cannot be bound. What's weird is if I take out all references to the subquery and leave just the query with the existing table and the temp table it joins fine, and also if I joint the existing table to just the sub suery it works just fine.
But when I try to put all 3 together it gives the me the "the multi-part identified z.[currnecy key] cannot be bound", which seems an odd error since this key is in an existing table and joins just fine to a temp table or sub query alone, but not both together.
I know about issues with joining on sub queries, but in this situation it seems that the issue seems to be with joining to sub queries and temp tables in the same query, which I'm not sure how to work around.
Code is below.
declare @tmpFx table (currency_key int, effective_date_key int, expiration_date_key int, to_usd float, from_usd float ) --primary key (currency_key, date_key))
insert into @tmpFx(currency_key, effective_date_key, expiration_date_key, to_usd, from_usd)
select [currency key], cast(convert(char(8),[effective date],112) as int), cast(convert(char(8),[expiration date],112) as int), [to usd], [from usd]
from v_fx --where [effective date] >= @beginDate
declare @fixedFx table (currency_key int, to_usd float, from_usd float primary key (currency_key))
insert into @fixedFx(currency_key, to_usd, from_usd)
select [currency key], [to usd], [from usd]
from v_fx where [effective date] = '2012-01-01'
select z.[currency key], --stat_fx.to_usd to_usd, stat_fx.from_usd from_usd, --q.*,--
stat_usd_amt2 = case when z.[currency key] = 100001 then q.orig_amt else 0 end --sum(q.orig_amt * stat_fx.to_usd)
from [dim country] z,
(select b.country_key, a.currency_key, a.data_type_key, sum(a.amount) orig_amt,
sum(a.amount * stat_fx.to_usd) stat_usd_amt,
sum((a.amount * stat_fx.to_usd) * stat_fx.from_usd) home_curr_amt
from tbl_cohort a
inner join tbl_management_code b on a.management_code = b.management_code
left outer join @tmpFx stat_fx on a.currency_key = stat_fx.currency_key
where a.data_type_key = 1
and a.date_key > 20111231
group by b.country_key, a.currency_key, a.data_type_key) q
inner join @tmpFx stat_fx on z.[currency key] = stat_fx.currency_key
where q.[country_key]= z.[country key]