放样结果查询加入

时间:2016-12-15 13:33:26

标签: sql vba ms-access

在Access中我有一个包含一些贷款的表和另外两个包含衍生物的表(列的名称几乎相同)

以下是表格:

表1

LoanNumber    MappingID  
Loan1         M1         
Loan2         M2  

表2

DerivativeANumber    MappingID    StartDate
DerA1                M1           1-1-2010
DerA2                M1           1-1-2012

表3

DerivativeBNumber  MappingID    StartDate
DerB1              M1           1-1-2005
DerB2              M2           1-1-2012

我想检索与每笔贷款相关的两种衍生产品中最低的StartDate(通过MappingID)。

例如,对于Loan1,我会得到:

LoanNumber  DerivativeNumber    StartDate
Loan1       DerB1               1-1-2005

我尝试过LEFT JOIN但无法想出将联接结果“堆叠”在一起的方法。

提前致谢!

2 个答案:

答案 0 :(得分:0)

未经测试,但与

相似
SELECT
    A.LoanNumber
    , MIN(StartDate) as Min_StartDate
FROM
    TABLE1 as A
    LEFT JOIN       
    (SELECT DerivativeANumber as DerivativeNumber, MappingID, StartDate FROM TABLE2)        
    UNION ALL
    (SELECT DerivativeBNumber as DerivativeNumber, MappingID, StartDate FROM TABLE3) as B
    ON (A.MappingID = B.MappingID)
GROUP BY
    A.LoanNumber

应该成为一个起点

  • 首先,将您的Table2Table3合并到一个表格中。

    有几种方法可以做到这一点,我使用UNION ALL,另一种方法是将INSERT数据转换为新的,暂时的表格

  • 因为我使用UNION ALL,所以我必须首先使用(SELECT DerivativeANumber as DerivativeNumber, MappingID, StartDate FROM TABLE2)(x2)重命名标题

  • 然后我们会查询您的UNION ALL的结果,通过按这些字段进行分组来计算Min(StartDate)的每个组合的LoanNumber

  • 然后,您将DerivativeNumber Left Join添加到合并的表格中。

希望有所帮助

答案 1 :(得分:0)

使用DISTINCT Top 1而不是Min()就可以了!非常感谢你们!

解决方案:

SELECT DISTINCT TOP 1
    A.LoanNumber
    , B.DerivativeNumber
    , StartDate as Min_StartDate
FROM
    TABLE1 as A
    LEFT JOIN       
    (SELECT DerivativeANumber as DerivativeNumber, MappingID, StartDate FROM TABLE2)        
    UNION ALL
    (SELECT DerivativeBNumber as DerivativeNumber, MappingID, StartDate FROM TABLE3) as B
    ON (A.MappingID = B.MappingID)    
WHERE A.LoanNumber = Loan1
ORDER BY StartDate