Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Lea Ibbs
Starting Member
3 Posts |
Posted - 2008-03-22 : 05:33:18
|
I am trying to set up a query to select PaymentDate, CustSurname, CustForename, AgentName showing only the last record for each customer if the last payment is over 7 days and also include customers with no payment. the table structure is:tblLoansLoanID (PK)CustID (FK)AgentID(FK)tblPaymentsPaymentID (PK)PaymentDateLoanID (FK)tblAgentsAgentID (PK)AgentNametblCustomersCustID (PK)CustSurnameCustforenameI have tried the code as below: but it now gives me every payment for the defaulters as opposed to just the last defaulted payment. Can you shed any light on what I have done wrong.select b.PaymentDate, a.CustSurname, a.Custforename, c.AgentName, d.LoanIDfrom tblCustomers a, tblPayments b, tblAgents c, tblLoans dwhere d.LoanID = b.LoanID and d.CustID = a.CustID and d.AgentID = c.AgentIDand (DATE()-(SELECT max(PaymentDate) from tblPayments f where f.LoanID=d.LoanID ))>7UNION select '' as PaymentDate, a.CustSurname, a.Custforename, c.AgentName, d.LoanIDfrom tblCustomers a, tblLoans d, tblAgents cwhere a.CustID = d.LoanIDand c.AgentID = d.AgentIDand (select count(*) from tblPayments where tblPayments.LoanID = d.LoanID) = 0; |
|
sqlleaf
Starting Member
3 Posts |
Posted - 2008-04-18 : 03:42:21
|
Hi. Would like to share some ideas here for your consideration.The second part of your SQL looks ok:UNION select '' as PaymentDate, a.CustSurname, a.Custforename, c.AgentName, d.LoanIDfrom tblCustomers a, tblLoans d, tblAgents cwhere a.CustID = d.LoanIDand c.AgentID = d.AgentIDand (select count(*) from tblPayments where tblPayments.LoanID = d.LoanID) = 0;For the first part, I think it selects all the payments that defaulted (over 7 days), so there could be multiple for a single customer.The following may eliminate payments defaulting on an earlier date, but if you have 2 payments with the same payment date, which is over 7 days, both will still be selected, and you need to fine-tune further:SELECT b.PaymentDate, a.CustSurname, a.Custforename, c.AgentName, d.LoanIDFROM tblCustomers AS a, tblPayments AS b, tblAgents AS c, tblLoans AS d, [SELECT CustID, max(PaymentDate) AS MaxPaymentDateFROM tblPayments AS f, tblLoans AS gWHERE f.LoanID=g.LoanIDGROUP BY CustID]. AS maxpWHERE d.LoanID = b.LoanID and d.CustID = a.CustID and d.AgentID = c.AgentIDand d.CustID = maxp.CustID and b.PaymentDate = maxp.MaxPaymentDateand (DATE()-maxp.MaxPaymentDate)>7UNION select '' as PaymentDate, a.CustSurname, a.Custforename, c.AgentName, d.LoanIDfrom tblCustomers a, tblLoans d, tblAgents cwhere a.CustID = d.LoanIDand c.AgentID = d.AgentIDand (select count(*) from tblPayments where tblPayments.LoanID = d.LoanID) = 0; |
 |
|
|
|
|
|
|