2011-02-15 89 views
2

我想完成的是从@ temp2中获取ID列以对应来自@ temp1的intA和intB列 我希望看到的最终结果输出会看起来像像:需要MS-SQL查询帮助

intA intB 'asset1' 'asset2' 'name1' 'name2' 

1 1 108 108 Cash Cash 

1 2 108 109 Cash Commodities 

1 3 108 138 Cash Stock 
. 
. 
. 

2 5 109 111 Commodities Equity 

这里是我一起工作的一些样本数据:

declare @temp1 table 
(
    intA int, 
    intB int 
) 
insert @temp1 
select 1,1 union all 
select 1,2 union all 
select 1,3 union all 
select 1,4 union all 
select 1,5 union all 
select 2,1 union all 
select 2,2 union all 
select 2,3 union all 
select 2,4 union all 
select 2,5 

select * from @temp1 
declare @temp2 table 
(
    oneup int, 
    id int, 
    name varchar(30) 
) 
insert @temp2 
select 1,108,'Cash' union all 
select 2,109,'Commodities' union all 
select 3,138,'Stock' union all 
select 4,110,'Bonds' union all 
select 5,111,'Equity' 

select * from @temp2 

select t1.*,t2.* from @temp1 t1 
inner join @temp2 t2 
on t1.intA = t2.oneup 

我不能让参加工作权给我一个输出像我期望的那样。 使用SQL2008

感谢您的任何帮助!

+0

+1包括样本数据。 – 2011-02-15 19:02:09

回答

1

您需要加入@temp2两次,一次为intA,一次为intB

select t1.intA, t1.intB, 
     t2a.id as asset1, t2b.id as asset2, 
     t2a.name as name1, t2b.name as name2 
    from @temp1 t1 
     inner join @temp2 t2a 
      on t1.intA = t2a.oneup 
     inner join @temp2 t2b 
      on t1.intB = t2b.oneup 
+0

完美!正是我在找什么。没有考虑使用第二次加入。谢谢! – 2011-02-15 19:07:38