简体   繁体   中英

Select 1st, 2nd, and 3rd rows for each person in Access

I have two tables: assets and people. A person may have 0 or more assets, like so:

ID, First, Last,   Name,          Email, Current Employee
218 Bob    Robert  Robert, Bob    1@a.b  Yes (-1)
249 Bill   Nobody  Nobody, Bill   2@a.b  No (0)
396 Steve  Stevens Stevens, Steve 3@a.b  Yes (-1)
549 John   Doe     Doe, John      4@a.b  Yes (-1)

Inventory ID, Date,    Model, Owner, Status
10001         1-1-2012 E6500  218    Active
10003         2-1-2012 E6500  396    Active
10005         1-1-2013 T1500  396    Active
10009         2-1-2013 T1500  218    Active
10059         3-1-2013 T1500  549    Inactive
10100         1-1-2015 T540p  218    Active
10150         1-1-2016 M81    218    Active

What I need help figuring out is how to display the newest first, second, and third Asset ID (not to be confused with the UID) and Model (and other columns) for each Owner, along with that people's First Name, Last Name, and Email, but only for employees who are current, like so:

Email, First,  Last, Inventory 1, Model 1, Inventory 2, Model 2, Inventory 3, Model 3
1@a.b  Robert  Bob   10150        M81      10100        T540P    10100        T1500
3@a.b  Stevens Steve 10005        T1500    10003        E6500

(There is nothing for Bill, as he is not a current employee, and nothing for John, as he has no active asset)

This is in Access (not my choice), unfortunately. I've tried so many different queries but couldn't figure it out at all.

Here is one rather brute force method, assuming that there are no duplicate dates for an owner:

select p.*,
       a1.inventory as inventory1, a1.model as model1,
       a2.inventory as inventory2, a2.model as model2,
       a3.inventory as inventory3, a3.model as model3
from ((people as p inner join
       assets as a1
       on a1.owner = p.id
      ) inner join
      assets as a2
      on a2.owner = p.id
     ) inner join
     assets as a3
     on a3.owner = p.id
where a1.date = (select max(date) from assets where assets.owner = p.id) and
      a2.date = (select max(date) from assets where assets.owner = p.id and assets.date < a1.date) and
      a3.date = (select max(date) from assets where assets.owner = p.id and assets.date < a2.date);

Note: This is so much easier in almost any other database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM