2017-04-18 173 views
0

你能幫助我嗎?加入查詢關係數據

樣本數據:

enter image description here

說明:

TableA is =IDAPK, No Urut(L1), No Tampil (L1), Text Faktor (L1) 

    TableB is =IDBPK, IDAFK, No Urut(L2), No Tampil (L2), Text Faktor (L2) 

    IDAPK=IDAFK (ForeignKkey) 

你可以加入使得SQL Server查詢要像結果上面的圖片?我找不到我的邏輯。 謝謝你...

+1

您想要的格式類型可能在您的表示層最好處理。您是否期望使用原始查詢來生成該輸出,或者您是否使用其他語言? –

+0

我正在使用SQL Server查詢... –

+0

您使用的是什麼報告工具?或者你只是出口到CSV或其他東西?你到目前爲止試過什麼樣的查詢?爲什麼需要以這種方式呈現 - 是否適合最終用戶? –

回答

1

我找到了一種方法來做到這一點。兩個query兩個table然後Union All那些result。檢查下面的SQL:

Select [No Urut(L1)],[No Tampil (L1)],[Text Faktor (L1)],[No Urut(L2)],[No Tampil (L2)],[Text Faktor (L2)] From 
(
    Select IDAPK As ID,1 As SL,[No Urut(L1)],[No Tampil (L1)],[Text Faktor (L1)],'' As [No Urut(L2)],'' As [No Tampil (L2)], '' As [Text Faktor (L2)] From TableA 
     Union All 
    Select IDAFK As ID,2 As SL,'' As [No Urut(L1)],'' As [No Tampil (L1)],'' As [Text Faktor (L1)],[No Urut(L2)],[No Tampil (L2)],[Text Faktor (L2)] From TableB 
) As TableAB Order By ID, SL 

輸出的SQL:

enter image description here

+0

您還需要添加一個'order by',因爲沒有order by –

+0

bro IDAPK is belong TableA not TableB .. TableB is IDAFK ..謝謝你@csharpbd –

+0

好工作兄弟..謝謝你... @csharpbd –

0

此查詢使用INNER JOIN所以它返回具有兩個表中的匹配值的記錄。

SELECT TableA.[No Urut(L1)], TableA.[No Tampil (L1)], TableA.[Text Faktor (L1)], TableB.[No Urut(L2)], TableB.[No Tampil (L2)], TableB.[Text Faktor (L2)] 
FROM TableA 
INNER JOIN TableB ON TableA.IDPK=TableB.IDFK;