2014-01-28 48 views
0

我目前根據Claim_NumberCustomer_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更長,我已經更改了表名等,但我希望你能明白。如果重要,我將根據此查詢創建視圖。

請提供有關如何正確高效地從同一表中選擇多個列的建議。謝謝!

+1

結果如何不正確?您確定'Product_Info'中的每個產品只有一行嗎? –

+0

這是問題。在某些產品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

+1

然後在連接條件中包含日期。 –

回答

0

我發現把我的額外的東西放入CTE中並添加ROW_NUMBER以確保我只得到我關心的1行。它看起來像這樣。我只爲第2個產品信息做過。

WITH PD_Info 
     AS (SELECT Product_ID 
       ,Product_Name 
       ,Effective_Date 
       ,ROW_NUMBER() OVER (PARTITION BY Product_ID, Product_Name ORDER BY Effective_Date DESC) AS RowNum 
      FROM Company.dbo.Product_Info) 
SELECT A.* 
     ,B.* 
     ,PD_Info_1.Product_Name 
     ,PD_Info_2.Product_Name 
    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 PD_Info AS PD_Info_1 
     ON B.Product_ID_1 = PD_Info_1.Product_ID 
      AND B.Fill_Date >= PD_Info_1.Effective_Date 
      AND PD_Info_2.RowNum = 1 
    LEFT JOIN PD_Info AS PD_Info_2 
     ON B.Product_ID_2 = PD_Info_2.Product_ID 
      AND B.Fill_Date >= PD_Info_2.Effective_Date 
      AND PD_Info_2.RowNum = 1 
+0

這正是我所需要的。謝謝! – user3006876

相關問題