2017-03-07 236 views
1

如何使用MS ACCESS上的分區轉換row_number()函數? 我想實現的是:(Ms Access)Row_Number()Over分區

從這個表:

ID | EntryDate 
10 | 2016-10-10 
10 | 2016-12-10 
10 | 2016-12-31 
10 | 2017-01-31 
10 | 2017-03-31 
11 | 2015-01-31 
11 | 2017-01-31 

此輸出,只顯示前3最新每個ID:

ID | EntryDate 
10 | 2016-12-31 
10 | 2017-01-31 
10 | 2017-03-31 
11 | 2015-01-31 
11 | 2017-01-31 

在SQL Server中,我可以使用以下代碼實現此目的:

select T.[ID], 
    T.[AptEndDate], 
from (
select T.[ID], 
     T.[AptEndDate], 
     row_number() over(partition by T.[ID] order by T.[AptEndDate] desc) as rn 
from Table1 as T 
) as T 
where T.rn <= 3; 

回答

0

任何東西使用OVER子句稱爲窗口函數。不幸的是,MS Access沒有在這種情況下,開窗Functions.The最簡單的解決方案的支持可能是回VBA代碼:(

+0

你有任何想法如何,我可以使用VBA代碼來實現呢? – user1688194

4

考慮計數相關子查詢可以在任何RDBMS工作。

select T.[ID], T.[EntryDate] 
from 
(select sub.[ID], 
     sub.[EntryDate], 
     (select count(*) from Table1 c 
      where c.ID = sub.ID 
      and c.[EntryDate] >= sub.[EntryDate]) as rn 
from Table1 as sub 
) as T 
where T.rn <= 3; 
1

這可能是更簡單,更快地使用前n個 - 你提到自己:

Select T.[ID], T.[EntryDate] 
From Table1 As T 
Where T.[EntryDate] In 
    (Select Top 3 S.[EntryDate] 
    From Table1 As S 
    Where S.[ID] = T.[ID] 
    Order By S.[EntryDate] Desc) 
Order By T.[ID] Asc, T.[EntryDate] Asc 
相關問題