2014-03-19 125 views
0

示例數據TSQL - 動態數據查詢

表1

Id Column 
1 J1 
2 J3 
3 J2 
4 J2 
5 J1 

表2

RecId J1  J2  J3 
1  1  NULL NULL 
2  1  2  NULL 
3  NULL 3  NULL 
4  NULL 2  NULL 
5  1  NULL NULL 

我需要這個結果

Id RecId Column Value 
1 1  J1  1 
2 2  J3  NULL 
3 3  J2  3 
4 4  J2  2 
5 5  J1  1 

回答

0

使用此代碼:

declare @Table1 as table(id int ,column1 nvarchar(10)) 

insert into @Table1(Id ,column1) values(1 ,N'J1') 
insert into @Table1(Id ,column1) values(2 ,N'J3') 
insert into @Table1(Id ,column1) values(3 ,N'J2') 
insert into @Table1(Id ,column1) values(4 ,N'J2') 
insert into @Table1(Id ,column1) values(5 ,N'J1') 

declare @Table2 as table (RecId int ,J1 int ,J2 int ,J3 int) 

insert into @Table2(RecId ,J1 ,J2 ,J3)values(1 ,1 ,NULL ,NULL) 
insert into @Table2(RecId ,J1 ,J2 ,J3)values(2 ,1 ,2 ,NULL) 
insert into @Table2(RecId ,J1 ,J2 ,J3)values(3 ,NULL ,3 ,NULL) 
insert into @Table2(RecId ,J1 ,J2 ,J3)values(4 ,NULL ,2 ,NULL) 
insert into @Table2(RecId ,J1 ,J2 ,J3)values(5 ,1 ,NULL ,NULL) 


select t1.id ,t2.RecId ,t1.column1 
     ,(Case t1.column1 
     when N'J1' then t2.J1 
     when N'J2' then t2.J2 
     when N'J3' then t2.J3 
     else NULL end) As Value 
From @Table1 As t1 
inner join @Table2 As t2 ON t1.id = t2.RecId 
+0

對不起,Js都是動態的,並沒有太限制,因爲這樣...我有解決方案,但只是想拋出這裏,以防有人有更好或更快的情況... – Juvil