我目前根據Claim_Number
和Customer_Number
加入兩個表格。如何在包含相同類型信息的同一個表中的多個列上進行聯接?
SELECT
A.*,
B.*,
FROM Company.dbo.Company_Master AS A
LEFT JOIN Company.dbp.Compound_Info AS B ON A.Claim_Number = B.Claim_Number AND A.Customer_Number = B.Customer_Number
WHERE A.Filled_YearMonth = '201312' AND A.Compound_Ind = 'Y'
這會返回我正在查找的數據。問題是,我現在需要加入到另一個表來獲取基於Product_ID
的信息。如果每個記錄的Compound_Info表中只有一個Product_ID,這很容易。然而,有10個。所以基本上我需要SELECT
根據Product_ID
的每個已被選中的Product_Name
增加10個列。怎麼可以做到這一點?這就是我腦海中想的,但並不正確。
SELECT
A.*,
B.*,
PD_Info_1.Product_Name,
PD_Info_2.Product_Name,
....etc {Up to 10 Product Names}
FROM Company.dbo.Company_Master AS A
LEFT JOIN Company.dbo.Compound_Info AS B ON A.Claim_Number = B.Claim_Number AND A.Customer_Number = B.Customer_Number
LEFT JOIN Company.dbo.Product_Info AS PD_Info_1 ON B.Product_ID_1 = PD_Info_1.Product_ID
LEFT JOIN Company.dbo.Product_Info AS PD_Info_2 ON B.Product_ID_2 = PD_Info_2.Product_ID
.... {Up to 10 LEFT JOIN's}
WHERE A.Filled_YearMonth = '201312' AND A.Compound_Ind = 'Y'
該查詢不僅不會返回正確的結果,而且還需要永遠運行。我的實際SQL更長,我已經更改了表名等,但我希望你能明白。如果重要,我將根據此查詢創建視圖。
請提供有關如何正確高效地從同一表中選擇多個列的建議。謝謝!
結果如何不正確?您確定'Product_Info'中的每個產品只有一行嗎? –
這是問題。在某些產品ID上有不同的產品名稱,取決於日期。我正在嘗試添加類似於加入的內容: LEFT JOIN Company.dbo.Product_Info AS PD_Info1 ON B.Product_ID_1 =(SELECT TOP 1 Product_ID FROM Company.dbo.Product_Info WHERE B.Fill_Date> = PD_Info_1.Effective_Date DESC) 任何要注意採取這種做法?謝謝! – user3006876
然後在連接條件中包含日期。 –