[英]Joining tables in oracle
我有一個像這樣的主數據表:
tableA
ID | tainfo1 | tainfo2
----------------------
1 | me | 100
2 | you | 200
3 | they | 300
和這樣的屬性表:
tableB:
ID | type | tbinfo1 | tbinfo2
------------------------------
1 | 1 | good | 7
1 | 2 | bad | 5
2 | 2 | so&so | 6
3 | 1 | awesome | 10
在屬性表中,我的type
集很小,我想知道是否有機會進行這樣的數據輸出。
ID | tainfo1 | tainfo2 | tbinfo1_type1 | tbinfo2_type1 | tbinfo1_type2 | tbinfo2_type2
-----------------------------------------------------------------------------------------
1 | me | 100 | good | 7 | bad | 5
2 | you | 200 | | | so&so | 6
3 | they | 300 | awesome | 10 | |
如果所有屬性都存在,則填充所有列,例如記錄1, _typeX
列也將顯示為空白,例如type1的記錄2
我希望問題清楚,
問候。
連接兩個表並透視結果:
select *
from (
select id, tainfo1, tainfo2, type, tbinfo1, tbinfo2
from tableA join tableB using (id))
pivot (max(tbinfo1) t1, max(tbinfo2) t2 for type in (1 info1, 2 info2))
輸出:
ID TAINFO1 TAINFO2 INFO1_T1 INFO1_T2 INFO2_T1 INFO2_T2
----- ---------- ---------- ---------- ---------- ---------- ----------
1 me 100 good 7 bad 5
2 you 200 so-so 6
3 they 300 awesome 10
這將適用於列type
定義數量的值。 Oracle 11g版本也提供了pivot
,對於較舊的版本,請使用max(decode...)
如此處 。 如果您需要完全動態的解決方案,請閱讀文章: link1 , link2 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.