我有两张桌子:资产和人。一个人可能拥有0个或更多资产,如下:
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
我需要帮助弄清楚如何显示每个所有者的最新的第一,第二和第三资产ID(不要与UID混淆)和模型(和其他列),以及该人的名字,姓氏和电子邮件,但仅适用于当前的员工,如下所示:
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
(Bill没有任何内容,因为他不是现任员工,John没有任何内容,因为他没有活跃资产)
不幸的是,这是在Access(不是我的选择)。我已经尝试了很多不同的查询,但根本无法弄明白。
答案 0 :(得分: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);
注意:几乎在任何其他数据库中都这么容易。