2016-04-25 147 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); 

注:這是所以在幾乎任何其他數據庫要容易得多。

相關問題