【发布时间】:2013-02-07 10:16:06
【问题描述】:
我有一个查询,我在开始时创建了 2 个临时表,然后我查询数据库中的现有表并将该表连接到子查询,然后最后连接到 1 个临时表。当我这样做时,我收到一个错误,即我从现有表中加入的键无法绑定。奇怪的是,如果我取出对子查询的所有引用,只留下现有表和它连接的临时表的查询,并且如果我将现有表连接到子查询,它工作得很好。
但是当我尝试将所有 3 个放在一起时,它给了我“无法绑定多部分标识的 z.[currnecy key]”,这似乎是一个奇怪的错误,因为该键位于现有表中并且只加入可以单独使用临时表或子查询,但不能同时使用。
我知道加入子查询的问题,但在这种情况下,问题似乎在于在同一个查询中加入子查询和临时表,我不确定如何解决。
代码如下。
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]
【问题讨论】:
-
这里的部分问题可能是您混合了两种不同的连接语法,这使得它很难理解。您正在使用 ANSI 标准
INNER和LEFT连接,但别名为q的内联视图作为逗号分隔的表列表的一部分连接。 -
另外,你能在 SQL Fiddle 上建立一个有代表性的例子吗?当我们不知道表格是什么时,很难发现问题。
标签: tsql sql-server-2005 subquery inner-join temp-tables