[英]Return single record from another table with multiple records per transactionDate
How can I create a query that will return the latest Soa LoanableAmount based on the LoanApplicationDate. 如何创建一个查询,该查询将基于LoanApplicationDate返回最新的Soa LoanableAmount。
Ex: For LoanID = 1, I want to get the Soa record with SoaID = 2 since this is the latest loanable amount for this LoanApplicationDate - 2017-07-01. 例如:对于LoanID = 1,我想获取SoaID = 2的Soa记录,因为这是此LoanApplicationDate-2017-07-01的最新可贷金额。
So far this is what I have accomplished: 到目前为止,这是我已经完成的工作:
select *
from Loan L
join Soa S
ON S.EmployeeID = L.EmployeeID
where S.TransactionDate <= L.LoanApplicationDate
To illustrate what I want to accomplish, please see screenshot below. 为了说明我要完成的工作,请参见下面的屏幕截图。
https://www.db-fiddle.com/f/3PBossUJLYQTQZJfZymiph/0 https://www.db-fiddle.com/f/3PBossUJLYQTQZJfZymiph/0
I think you need to set the condition on the join: 我认为您需要为连接设置条件:
select
L.LoanID,
L.EmployeeID,
L.LoanAmount,
L.LoanApplicationDate,
S.LoanableAmount,
S.TransactionDate
from Loan L join Soa S
ON S.EmployeeID = L.EmployeeID and
S.TransactionDate = (select max(TransactionDate) from Soa where TransactionDate <= L.LoanApplicationDate)
I think you want a join
and then to filter to get the most recent date: 我认为您想要
join
然后进行过滤以获取最新日期:
select l.*, s.*
from Loan l join
Soa s
on s.employeeid = l.employeeid
where s.TransactionDate <= (select max(s2.TransactionDate)
from Soa s2
where s2.employeeid = l.employeeid and
s2.TransactionDate <= l.LoanApplicationDate
);
The below query will give you all employee ids with loanable amount withdrawn on latest date 以下查询将为您提供所有雇员ID,并在最近日期提取可贷金额
Select employee_id,
LoanableAmount
transactionDate from table
having
transactionDate=max(transactionDate)
group by employee_id
You need to run a subquery for each row: 您需要为每行运行一个子查询:
select q.*, S.LoanableAmount, S.TransactionDate from
(select
L.*
,(select SoaID from Soa x where x.EmployeeID = L.EmployeeID and x.TransactionDate <= L.LoanApplicationDate order by TransactionDate DESC limit 1) as SoaID
from Loan L) q
join Soa S on S.SoaID = q.SoaID
Line 4 will give you the SoaID of the row in the Soa table that has the newest date that is less than or equal to the Application Date, then with that ID you just join and show the rest of the fields. 第4行将为您提供Soa表中行的SoaID,该行的最新日期小于或等于“应用程序日期”,然后使用该ID进行联接并显示其余字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.