如何在同一个表中包含相同类型信息的多个列上加入?

时间:2014-01-28 17:35:50

标签: sql sql-server left-join

我目前正在根据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 10个Product_Name的其他列,这些列基于已经选择的每个Product_ID。怎么办?这就是我脑子里的想法,但是效果不好。

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 个答案:

答案 0 :(得分:0)

我发现将我的额外内容放入CTE并添加ROW_NUMBER以确保我只得到我关心的一行。看起来像这样。我只做了前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