Sql连接3个表查询贷款总结果

时间:2017-11-13 11:48:10

标签: sql sql-server sql-server-2008

我必须从3个表中获得客户贷款总额,这两个表被贷款给sum,另一个表减去付款金额,表格中有客户ID。到目前为止,只有当所有表中都存在客户ID时,我才能得到结果,但如果它不存在于一个表中,我就不会在我的结果中获得客户。或者当我锚定给客户时,我得到NULL客户ID。

SELECT 
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) + 
  ISNULL(AS2.NewGivenLoan, 0) - 
  ISNULL(AS3.LoanPaid,0) ) AS Total 
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT 
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan 
    FROM 
       Money_On_Customer MOC (NOLOCK)
    GROUP BY 
       MOC.C_ID) AS1 
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN 
(SELECT 
       NGL.C_ID 
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan 
    FROM 
       Given_Loan NGL   
    GROUP BY 
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN 
   (SELECT 
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid 
    FROM 
       Given_Loan_Paid GLP 
    GROUP BY 
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id

这是我的两个结果的图片:

When I get NULL Customer IDs

When I don't get All the Customers

3 个答案:

答案 0 :(得分:0)

您需要将c.c_id用于第一列

为了只获取至少其中一个表中存在的记录,您可以将其添加到查询中,只需将当前查询替换为点,然后添加leftid col

Select * 
From
(Select c.c_id custonerid, 
        Coalesce(Coalesce(as1.c_id,as2.c_id),as3.c_id) leftid,......
 From ....
) ilv
Where leftid is not null

您可以添加

Where coalesce(coalesce(as1.c_id,as2.c_id),as3.c_id) is not null 

然后结束查询

答案 1 :(得分:0)

答案 2 :(得分:-1)

在@Ab Bennett的帮助下,这是我的答案

Select * 
  From
  ( 
   SELECT 
     C.C_Name AS [Customer ID],
     ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
     ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
     ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
     (ISNULL(AS1.OldCustomerLoan, 0) + 
     ISNULL(AS2.NewGivenLoan, 0) - 
     ISNULL(AS3.LoanPaid,0) ) AS Total 
   FROM
    Customer C
    LEFT OUTER JOIN
     (SELECT 
        MOC.C_ID,
        SUM(MOC.Quantity) AS OldCustomerLoan 
   FROM 
       Money_On_Customer MOC (NOLOCK)
    GROUP BY 
       MOC.C_ID) AS1 
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN 
     (SELECT 
       NGL.C_ID 
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan 
       FROM 
       Given_Loan NGL   
    GROUP BY 
    NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
    LEFT OUTER JOIN 
     (SELECT 
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid 
    FROM 
       Given_Loan_Paid GLP 
    GROUP BY 
       GLP.C_ID ) AS3
   ON c.C_Id = AS3.C_Id) ilv
   Where not ([Old Loan] = 0 and [New Given Loan]=0 and PaidLoanAmount =0 )