TSQL - 动态数据查询

时间:2014-03-19 01:01:03

标签: 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

1 个答案:

答案 0 :(得分: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