SQL JOIN和SUB QUERY

时间:2017-07-20 04:09:35

标签: sql

下面是两个表客户信息和第二个客户的贷款和还款我想加入这两个表并检索图片中的预期结果,请注意在第二个表中,一个客户可以拥有多个贷款,并且他/她可以在第二个表中以多个分期偿还它,它保存在许多行中,我期望加入这两个表并检索仍欠的客户公司。

我发现预期结果是一个很好的解决方案,但无法检索预期的结果。

如果你有一个很好的解决方案,而不是预期的结果,请分享。

例如: -

enter image description here

我尝试了下面的查询,但它不起作用,因为客户端ID号1在显示树时间时发放了三倍贷款用途它显示了贷款总额的三倍

SELECT DISTINCT 
CUSTOMER_AIB_INFO_TABLE.ID, 
CUSTOMER_AIB_INFO_TABLE.NAME,
( 
    SELECT SUM (CUSTOMER_AIB_LOAN_TABLE.LOAN) AS "Total Loan" 
    FROM CUSTOMER_AIB_LOAN_TABLE 
    WHERE CUSTOMER_AIB_INFO_TABLE.ID = CUSTOMER_AIB_LOAN_TABLE.FK_ID
) AS "Loan", 

( 
    SELECT SUM (CUSTOMER_AIB_LOAN_TABLE.REPAYMENT) FROM CUSTOMER_AIB_LOAN_TABLE 
    WHERE CUSTOMER_AIB_INFO_TABLE.ID = CUSTOMER_AIB_LOAN_TABLE.FK_ID
) AS Repayment , 

CUSTOMER_AIB_LOAN_TABLE.PURPOSE 
FROM CUSTOMER_AIB_INFO_TABLE 
INNER JOIN CUSTOMER_AIB_LOAN_TABLE 
ON CUSTOMER_AIB_INFO_TABLE.ID = CUSTOMER_AIB_LOAN_TABLE.FK_ID

1 个答案:

答案 0 :(得分:0)

您可以在id

的select table group上使用内部联接,而不是Subquery
SELECT DISTINCT 
    CUSTOMER_AIB_INFO_TABLE.ID, 
    CUSTOMER_AIB_INFO_TABLE.NAME,
    T.Total_Loan AS "Loan",
    T.Total_Rep AS Repayment, 
    CUSTOMER_AIB_LOAN_TABLE.PURPOSE 
FROM CUSTOMER_AIB_INFO_TABLE 
INNER JOIN (

  SELECT CUSTOMER_AIB_LOAN_TABLE.FK_ID as FK_ID,
            SUM (CUSTOMER_AIB_LOAN_TABLE.LOAN) AS Total_Loan 
          ,  SUM (CUSTOMER_AIB_LOAN_TABLE.REPAYMENT) AS Total_Rep 
      FROM CUSTOMER_AIB_LOAN_TABLE 
      GROUP BY CUSTOMER_AIB_LOAN_TABLE.ID

      ) T on t.FK_ID = CUSTOMER_AIB_INFO_TABLE.ID