2017-10-09 57 views
0

主表:Select * from Table1如何獲得只有從三個表的匹配數據

Id Name1 Name2 

101 ttt sss 

二表:Select * from Table2

SId Id Colum1 Column2 Column3 

1 101 hhh  xxx erre 

2 101 wsa  tgf  fdfd 

三表:Select * from Table3

TId Id TColumn1 Tcolumn2 

5 101 uyt  uyu 

我的查詢:

Select * from Table1 t1 
Join Table2 t2 on t2.Id= t1.Id 
Join Table3 t3 on t3.Id= t1.Id 

我喜歡這個

Id Colum1 Column2 Column3 TColumn1 Tcolumn2 

1 hhh  xxx erre  uyt   uyu 

2 wsa  tgf  fdfd  uyt   uyu 

geeting數據我想是我的數據

Id Colum1 Column2 Column3 TColumn1 Tcolumn2 

1 hhh  xxx erre  uyt   uyu 

2 wsa  tgf fdfd  null   null 
+0

DId你已經嘗試使用「左外連接」而不是「連接」? – Tyron78

+0

規則是 - 除了第一行之外,總是有NULL的? – DhruvJoshi

回答

1

的你可以用下面的查詢

; with cte as 
    (
    Select 
    Colum1, 
    Column2, 
    Column3, 
    TColumn1, 
    Tcolumn2, 
    row_number() over(partition by t2.id order by SId asc) r 
    from Table1 t1 
    Join Table2 t2 on t2.Id= t1.Id 
    Join Table3 t3 on t3.Id= t1.Id 
    ) 

Select 
Colum1, 
Column2, 
Column3, 
TColumn1 =case when r=1 then TColumn1 else NULL end, 
Tcolumn2 =case when r=1 then Tcolumn2 else NULL end 
from cte 

See working demo

相關問題