我尝试创建一个连接两个表的视图,并返回截至特定日期的相关地址详细信息。
我有两张桌子:
员工:
ID (Primary key)
Name
EmployeeAddress:
ID (PK), (FK to Employee.ID)
DateValidFrom (PK)
AddressLine1
AddressLine2
PostCode
如何将两者结合起来以获取员工详细信息和某个日期的地址?
答案 0 :(得分:1)
您可以使用外部应用:
来执行此操作select
E.ID,
E.Name,
A.AddressLine1,
A.AddressLine2,
A.PostCode
from
Employee E
outer apply (
select top 1
A.AddressLine1,
A.AddressLine2,
A.PostCode
from
EmployeeAddress A
where
A.ID = E.ID and
A.DateValidFrom < getdate()
order by
A.DateValidFrom desc
) A
答案 1 :(得分:1)
执行此操作的一种方法是使用查找为每个id找到最新datevalidfrom的查询,并将其用作您加入其他表的派生表,如下所示:
select * from employee e
join employeeaddress ea on e.id = ea.id
join (select id, max(datevalidfrom) as max_date from employeeaddress group by id) ea2
on ea.id = ea2.id and ea.datevalidfrom = ea2.max_date
通过连接派生表中的max(datevalidfrom),您可以将查询的其余部分(可以获得所有行)限制为最新的。
并将其转变为视图:
create view employee_latest_address as
select e.id, e.name, ea.datevalidfrom, ea.addressline1, ea.addressline2, ea.postcode
from employee e
join employeeaddress ea on e.id = ea.id
join (select id, max(datevalidfrom) max_date from employeeaddress group by id) ea2
on ea.id = ea2.id and ea.datevalidfrom = ea2.max_date