2011-02-15 88 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