2014-08-29 173 views
0

我迷失在這一個,我是一個Access和SQL的新手,我已經搜索該網站和谷歌爲這個答案。MS Access - 返回值由最大日期

我有一個包含3個列的表,其中包含ID到其他表,然後日期。

列1(角色ID)第2欄(ActionID)第3列(SettingID)柱4(日期)

我需要組由第1列和第2列(這樣的這些獨特的組合)。可能會有多個具有不同SettingID的實例,區分日期。

我認爲總計選擇查詢完成這項工作,分組依據爲Column1和2,然後使用Max作爲日期列。但是我只是想要列3的值,而不是總數。

有沒有簡單的方法來做到這一點,我失蹤了?

+0

謝謝你的幫助!似乎我需要學習更多的SQL理論,因爲答案非常合理,我試圖使用查詢的設計模式構建它 - 我無法看到如何使用Access中的設計模式創建此查詢。 – 2014-08-29 12:54:50

回答

0
select roleid, actionid, settingid 
from your_table t1 
inner join 
(
    select roleid, actionid, max(date) as mdate 
    from your_table 
    group by roleid, actionid 
) t2 on t1.roleid = t2.roleid 
    and t1.actionid = t2.actionid 
    and t1.date = t2.mdate 
+0

感謝您的快速回復juergen :)我使用的是Access 2007,當我嘗試保存您的建議時,它說'FROM子句中的語法錯誤',然後突出顯示JOIN。 – 2014-08-29 10:42:16

+0

這是一個選擇查詢或是t2意味着正在創建一個表作爲此sql的結果? – 2014-08-29 10:43:49

+0

't2'是子查詢的別名。 – 2014-08-29 11:15:42

0

如果這是真的老版本的Access的話,就不會支持子查詢很好

您可以通過創建一個單獨的查詢

select roleid, actionid, max(date) as mdate 
from your_table 
group by roleid, actionid 

保存爲MaxDateQuery工作,這輪或類似的東西

然後,您可以在後續查詢中使用該保存的訪問查詢來獲得你想要的東西

select 
your_table.roleid, 
your_table.actionid, 
your_table.settingid 
from your_table 
inner join MaxDateQuery 
on your_table.roleid = MaxDateQuery.roleid 
and your_table.actionid = MaxDateQuery.actionid 
and your_table.date  = MaxDateQuery.mdate