信息最少的简化问题如下:
我有2个源表:
表A:
Col: 1 2 3 4 5
Data: 18 15 16 17 10
表B:
Col: 1 2 3 4 5
Data: 81 51 61 71 99
第三个表包含"指令":
表3:
ID Source
1 A
2 A
3 B
4 A
5 B
根据表3告诉我的情况,我需要从表A和B中选择值,以形成结果表:
Col: 1 2 3 4 5
Data: 18 15 61 17 99
答案 0 :(得分:1)
试试这个 -
<强>模式强>
create table TableA (col int, data1 int);
create table TableB (col int, data1 int);
create table TableC (col int, Source1 varchar(100));
insert into TableA values (1, 18), (2, 15), (3, 16);
insert into TableB values (1, 81), (2, 51), (3, 61);
insert into TableC values (1, 'A'), (2, 'A'), (3, 'B');
<强>查询强>
SELECT o.col
,CASE
WHEN o.Source1 = 'A'
THEN a.data1
ELSE b.data1
END data
FROM TableC o
LEFT JOIN TableA a ON o.col = a.col
AND o.Source1 = 'A'
LEFT JOIN TableB b ON o.col = b.col
AND o.Source1 = 'B'
<强>结果强>
Col Data
---------
1 18
2 15
3 61
<强> ---------- ---------更新强>
好的,根据讨论,您需要使用动态查询。您需要先从tablec
构建列,然后使用动态查询,如下所示。
DECLARE @cols AS NVARCHAR(MAX)
,@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((
SELECT CASE
WHEN c.Source1 = 'A'
THEN ',' + 'a.[' + cast(c.Col AS VARCHAR(4)) + ']'
ELSE ',' + 'b.[' + cast(c.Col AS VARCHAR(4)) + ']'
END
FROM TableC c
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT ' + @cols + ' FROM TableA a
FULL OUTER JOIN TableB b ON 1 = 1'
EXECUTE sp_executesql @query;
<强>结果强>
1 2 3 4
--------------
18 15 61 17
答案 1 :(得分:1)
可能有更好的方法,但这有效。
SELECT
CASE WHEN (SELECT Source FROM Table3 WHERE ID = 1) = 'A' THEN a.[1] ELSE b.[1] END
, CASE WHEN (SELECT Source FROM Table3 WHERE ID = 2) = 'A' THEN a.[2] ELSE b.[2] END
, CASE WHEN (SELECT Source FROM Table3 WHERE ID = 3) = 'A' THEN a.[3] ELSE b.[3] END
, CASE WHEN (SELECT Source FROM Table3 WHERE ID = 4) = 'A' THEN a.[4] ELSE b.[4] END
, CASE WHEN (SELECT Source FROM Table3 WHERE ID = 5) = 'A' THEN a.[5] ELSE b.[5] END
FROM dbo.TableA a
JOIN TableB b ON 1=1