2016-04-25 136 views
1

我有两个表格:资产和人员。一个人可以有0或更多的资产,像这样:为Access中的每个人选择第一行,第二行和第三行

ID, First, Last, Name,   Email, Current Employee 
218 Bob Robert Robert, Bob [email protected] Yes (-1) 
249 Bill Nobody Nobody, Bill [email protected] No (0) 
396 Steve Stevens Stevens, Steve [email protected] Yes (-1) 
549 John Doe  Doe, John  [email protected] 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 

我需要帮助搞清楚是如何首先显示最新的,第二和第三资产I​​D(不要与UID混淆)和型号(和其他列)对于每个所有者,与人的姓,名和电子邮件一起,但仅限于员工谁是当前的,就像这样:

Email, First, Last, Inventory 1, Model 1, Inventory 2, Model 2, Inventory 3, Model 3 
[email protected] Robert Bob 10150  M81  10100  T540P 10100  T1500 
[email protected] Stevens Steve 10005  T1500 10003  E6500 

(没有什么比尔,因为他是不是现任员工,对John来说什么都没有,因为他没有活动资产)

这是在Ac (不是我的选择),不幸的是。我已经尝试了很多不同的查询,但根本找不到它。

回答

0

这是一个相当强力的方法,假设有一个业主没有重复日期:

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); 

注:这是所以在几乎任何其他数据库要容易得多。