我的建议是UNPIVOT的数据Table2
这样你就可以轻松地对数据结合,那么你就可以返回table1的描述和table2 id。使用CROSS此查询的UNPIVOT部分适用于:
select col, value, t2.Id
from table2 t2
cross apply
(
select 'table1id1', table1id1 union all
select 'table1id2', table1id2 union all
select 'table1id3', table1id3
) c (col, value);
见SQL Fiddle with Demo。这给出了一个结果:
| COL | VALUE | ID |
---------------------------
| table1id1 | 1 | 1 |
| table1id2 | 2 | 1 |
| table1id3 | 3 | 1 |
| table1id1 | 2 | 2 |
| table1id2 | 3 | 2 |
| table1id3 | (null) | 2 |
| table1id1 | 3 | 3 |
现在,你有行中的数据,你可以很容易地加入对value
列返回id
:
select t1.description,
d.id
from table1 t1
inner join
(
select col, value, t2.Id
from table2 t2
cross apply
(
select 'table1id1', table1id1 union all
select 'table1id2', table1id2 union all
select 'table1id3', table1id3
) c (col, value)
) d
on t1.id = d.value
order by t1.description, d.id;
见SQL Fiddle with Demo
如果你真的想要使用UNPIVOT,那么您可以使用以下不多于每个表加入的结果:
select t1.description, t2.id
from table1 t1
inner join
(
select id, col, value
from
(
select id, [Table1ID1], [Table1ID2], [Table1ID3]
from table2
) d
unpivot
(
value for col in ([Table1ID1], [Table1ID2], [Table1ID3])
) unpiv
) t2
on t1.id = t2.value
order by t1.description, t2.id;
参见SQL Fiddle with Demo。
的UNPIVOT和CROSS应用正在做同样的事情,作为一个UNION ALL查询:
select t1.description, t2.id
from table1 t1
inner join
(
select id, 'table1id1' col, table1id1 value
from table2
union all
select id, 'table1id2' col, table1id2
from table2
union all
select id, 'table1id3' col, table1id3
from table2
) t2
on t1.id = t2.value
order by t1.description, t2.id;
见SQL Fiddle with Demo
CROSS APPLY与UNPIVOT做同样的事情。 – Taryn
感谢您花费在此上的时间......我选择了@JamieSee作为回答,因为它应用UNPIVOT要干净得多。它看起来像我只能选择一个作为答案,或者我会选择两个。再次感谢! – blub
@blub虽然这个答案可以让你得到结果,但为了得到最终结果,你无需多次加入你的表。你看过这个版本的执行计划还是我提供的版本?如果您真的想要使用UNPIVOT,我收录了一个不需要4个连接的版本。 – Taryn