SQL查询:JOIN三个表然后在加入第三个表后没有显示结果

时间:2018-02-26 03:57:17

标签: sql zoho

我有三张表如下:

LoanMaster表

LoanID  BranchName  DisbursementDate  DisbursementAmount
12345   H1          01-01-18          25000
12346   A1          05-01-18          20000
12347   M1          06-02-18          16000

收集表

LoanID  TransactionDate Amount
12345   05-02-18        500
12346   06-02-18        600

OverdueCollection表

LoanID  TransactionDate Amount
12345   05-02-18    200
12346   07-02-18    300

必需的输出

LoanID  BranchName  TransactionDate Collection Amount   Overdue Amount  
12345   H1          05-02-18        500                 200 
12346   A1          06-02-18        600                 NULL    
12346   A1          07-02-18        NULL                300 
12347   M1          NULL            NULL                NULL    

我已应用以下两个查询来获取两个表连接

“QRY_Test2”:

SELECT   c.LoanID LoanID, date(c.TransactionDate) TransDate, (c.Amount) Amt,
         d.Amount = NULL FROM  Collection c 
UNION
SELECT  d.LoanID LoanID, date(d.TransactionDate) TransDate, c.Amount = NULL,
         (d.Amount) as Amt FROM  Overdue Amount d 

然后分组以获取唯一结果,命名为finalTable:

SELECT LoanID, TransDate, sum("Amount"), sum("Amt") FROM  "QRY_Test2"
GROUP BY LoanID, TransDate 

然后我得到以下结果:

LoanID  TransactionDate Collection Amount   Overdue Amount  
12345   05-02-18        500                 200 
12346   06-02-18        600                 NULL    
12346   07-02-18        NULL                300 

然后,如果我将左连接应用于LoanMaster,我得不到任何结果:

Select LoanID, BranchName, TransactionDate, CollectionAmount, OverdueAmount from LoanMaster lm LEFT JOIN on FinalTable f lm.LoanID = f.loanid

只是想了解问题是什么,我需要上面提到的所需输出。

1 个答案:

答案 0 :(得分:2)

这里的挑战是生成一个表格,其中包含一个记录中给定日期和贷款的收集和逾期金额。我们可以使用CollectionOverdueCollection表的联合,然后通过贷款和日期进行转换。然后,只需将贷款主表连接到此子查询。

SELECT
    lm.LoanID,
    lm.BranchName,
    t.TransactionDate,
    t.CollectionAmount,
    t.OverdueAmount
FROM LoanMaster lm
LEFT JOIN
(
    SELECT LoanID, TransactionDate,
        MAX(CASE WHEN type = 1 THEN Amount END) AS CollectionAmount,
        MAX(CASE WHEN type = 2 THEN Amount END) AS OverdueAmount
    FROM
    (
        SELECT LoanID, TransactionDate, Amount, 1 AS type
        FROM Collection
        UNION ALL
        SELECT LoanID, TransactionDate, Amount, 2
        FROM OverdueCollection
    ) t
    GROUP BY
        LoanID, TransactionDate
) t
    ON lm.LoanID = t.LoanID;