2017-04-21 73 views
-3

我正在尋找一個解決方案,以從表Table 1和Table結果。請參閱下面的圖像的詳細信息加入兩個表中的SQL

enter image description here

Table1.OrderID = Table2.OrderID

我不是尋找一個簡單的連接查詢。在輸出Table1中值不重複。

+2

這是一個基本的JOIN。向我們展示您的查詢嘗試! – jarlh

+1

請將腳本和數據作爲文本發佈,而不是圖片。 – etsa

+1

請做一些研究,這不是你需要在這裏問的問題,你可以通過快速搜索找到答案。 – Tanner

回答

1

,最後我得到了什麼,我正好在尋找

的解決方案
WITH MasterTable as (SELECT ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY OrderID ASC) AS SlNo,* FROM Table1), 
DetailTable as (SELECT ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY OrderID ASC) AS SlNo,* FROM Table2) 

SELECT * FROM MasterTable A FULL JOIN DetailTable B 
ON A.OrderID = B.OrderID AND A.SlNo=B.SlNo 
ORDER BY B.OrderID 
+0

好哥們。你釘了它。好的:-) –

2
select Table1.*, Table2.Items, Table2.Quantity -- List the columns you want. I've specified the table name to avoid ambiguous column errors, and * means all columns 
from Table1 
inner join Table2 -- This is a join (inner gets only the records that exist in both tables) 
on Table1.OrderID = Table2.OrderID -- This is the join condition, you define which columns are the same between the tables 

而對於空白位,因爲你缺乏的意識在顯示層來處理這個:

with CTE as 
(
select Table1.*, 
     Table2.Items, 
     Table2.Quantity, 
     row_number() over(partition by Table1.OrderID order by Items) as rn 
    from Table1 
    inner join Table2 
    on Table1.OrderID = Table2.OrderID 
) 

select case when rn = 1 then OrderID end as OrderID, 
     case when rn = 1 then CustomerName end as CustomerName , 
     case when rn = 1 then CTE.Desc end as Desc, 
     Items, 
     Quantity 
from CTE 
+0

我不想查找連接查詢。請重新檢查我的結果。在輸出Table1中值不重複。這將是空白 –

0

您可以通過使用ROW_NUMBER()OVER(PARTITION BY ORDER BY)實現這一結果 代碼:

select 
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY tb1.orderid ORDER BY tb1.orderid) = 1 THEN tb1.orderid ELSE null END AS orderid, 
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY tb1.custname ORDER BY tb1.orderid) = 1 THEN tb1.custname ELSE '' END AS custname, 
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY tb1.Descp ORDER BY tb1.orderid) = 1 THEN tb1.Descp ELSE '' END AS Descp, 
    tb2.item,tb2.quentity 
    from tb1 inner join tb2 on tb1.orderid=tb2.orderid 

輸出:

orderid custname Descp item quentity 
    1 Ccustomer1 1item Pen  1 
    2 Ccustomer2 2item Ball 2 
          Bat 1 
    3 Ccustomer3 3item Book 2 
          Box  1 
          Bag  1 
          Pen  2