我创建了一个简单的Access数据库,其中包含表结构和查询的示例。两个表,人员(包含3个记录)和地址(包含5个记录),提供了为每个人捕获多个地址的功能。我对正常的条件语句很满意,但是这让我陷入了循环... 我正在寻找一个查询,该查询将仅返回给定人员的最新地址。 Table Relationship
查询的当前SQL:
SELECT Person.PersonID_PK, Address.Address, Address.StatusDate FROM Person INNER JOIN Address ON Person.[PersonID_PK] = Address.PersonID_FK;
我目前的回报:
EmployeeID_PK Address StatusDate 1 12 Elm St, MN 23569 11/13/2017 1 15 Apple Ln, NY 12345 7/15/2018 2 30 Mulberry, TN 38456 6/11/2018 2 10 Lonesome Pine, KY 15487 12/4/2018 3 100 Plaze Place, LA 14563 6/17/2018
我需要返回每个人以及最大(最新)的StatusDate 我的预期回报应该是:
EmployeeID_PK Address StatusDate 1 15 Apple Ln, NY 12345 7/15/2018 2 10 Lonesome Pine, KY 15487 12/4/2018 3 100 Plaze Place, LA 14563 6/17/2018
答案 0 :(得分:3)
您可以使用相关子查询:
User updatedUser = new User();
updatedUser.OnPremisesExtensionAttributes = new OnPremisesExtensionAttributes();
updatedUser.OnPremisesExtensionAttributes.ExtensionAttribute8 = "1";
答案 1 :(得分:0)
使用具有排名功能的CTE可以很好地工作。
;WITH empaddress AS
(
SELECT person.personid_pk,
address.address,
address.statusdate,
Dense_rank() OVER (partition BY id ORDER BY statusdate DESC) AS d_rank
FROM person
INNER JOIN address
ON person.[PersonID_PK] = address.personid_fk; )
SELECT person.personid_pk,
address.address,
address.statusdate
FROM empaddress
WHERE d_rank = 1;
答案 2 :(得分:0)
感谢您的帮助。我修改了戈登的代码以支持我的查询,以下提供了答案。
SELECT Person.PersonID_PK, Address.Address, Address.StatusDate
FROM Person
INNER JOIN Address
ON Person.[PersonID_PK] = Address.PersonID_FK
WHERE (((Address.StatusDate)=(SELECT MAX(Address.StatusDate)
FROM Address
WHERE Person.PersonID_PK = Address.PersonID_FK)));