MS Access中按组分组的前5条记录

时间:2017-10-05 09:36:26

标签: sql ms-access

以下代码返回所有记录: -

SELECT b.BROKERAGE_NAME, q.VAL_DATE
FROM TBLQUOTESNEW q LEFT JOIN TBLBROKERAGESNEW b ON q.BROKERAGE_ID = b.ID
WHERE q.VAL_DATE Is Not Null

是否可以为每个BROKERAGE_NAME返回前5条记录,其中VAL_DATE正在降序?

包括

    Brokerage A    02/10/2017
    Brokerage A    02/10/2017
    Brokerage A    02/10/2017
    Brokerage A    02/10/2017
    Brokerage A    01/10/2017
    Brokerage B    06/06/2016

排除(不在前5名)

    Brokerage A    30/09/2017

1 个答案:

答案 0 :(得分:1)

SELECT TOP 5 
      b.BROKERAGE_NAME,
      q.VAL_DATE
FROM 
      TBLQUOTESNEW q 
LEFT JOIN 
      TBLBROKERAGESNEW b 
      ON q.BROKERAGE_ID = b.ID
WHERE 
      q.VAL_DATE Is Not Null 
GROUP BY 
      BROKERAGE_NAME 
ORDER BY 
      VAL_DATE DESC`