我的建議是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