问题
I have a transaction table with relevant data and username. and also, there is a another table that stores staff's title history by date. However, title history table doesnt have log of every single day.
Here is an example of my transaction table:
username tran_date amount
-------- ---------- ------
anderson 16/02/2019 1200
julie 17/02/2019 54000
williams 20/02/2019 32650
and staff's title log table:
username date title
-------- ---- ------
anderson 01/01/2019 assistant
anderson 06/04/2019 chief
williams 07/03/2019 chief
julie 15/02/2019 technician
julie 27/05/2019 chief technician
I would like to join with the title of staff on the closest day. as in;
username tran_date amount title
-------- ---------- ------ ------
anderson 16/02/2019 1200 assistant
julie 17/02/2019 54000 technician
williams 20/02/2019 32650 chief
I have tried something blindly but nothing seems to logical :)
thanks for help!
回答1:
In SQL Server, you would express this using outer apply:
select t.username, t.tran_date, l.title
from transactions t outer apply
(select top (1) l.*
from log_table l
where l.username = t.username and l.date <= t.tran_date
order by l.date desc
) l ;
outer apply is SQL Servers equivalent to left join lateral.
来源:https://stackoverflow.com/questions/62127422/determining-the-staffs-title-when-a-certain-transaction-is-done