我有一个表,我想从Access 2010开始每周从ErrorMargin返回前3条记录。
我遇到的问题是0值被忽略,并且我希望在平局的情况下仅看到1条记录,其中平局将使记录总数超过3条。
我拥有的表是: NB:创建表的底部的VBA。
TMID WeekCommencing ErrorMargin 1 05-Oct-15 0 1 12-Oct-15 2 3 05-Oct-15 1 3 12-Oct-15 1 8 12-Oct-15 2 9 05-Oct-15 0.333333333 9 12-Oct-15 4 12 05-Oct-15 0 12 12-Oct-15 1.5
我目前拥有的SQL是:
SELECT T1.TMID, T1.WeekCommencing, T1.ErrorMargin, COUNT(*) FROM qry_REP_ErrorMargin T1 INNER JOIN qry_REP_ErrorMargin T2 ON T1.ErrorMargin <= T2.ErrorMargin AND T1.WeekCommencing = T2.WeekCommencing GROUP BY T1.TMID, T1.WeekCommencing, T1.ErrorMargin HAVING COUNT(*) <= 3 ORDER BY T1.WeekCommencing, T1.ErrorMargin
这将返回下表,该表仅显示2015年5月10日的两条记录- 还有另外两条记录的ErrorMargin为0,我希望它也返回其中一条。没关系。TMID和WeekCommencing字段将构成表的关键字段。
TMID WeekCommencing ErrorMargin Expr1003 9 05/10/2015 0.33 2 3 05/10/2015 1 1 1 12/10/2015 2 3 8 12/10/2015 2 3 9 12/10/2015 4 1
我曾尝试过其他解决方案,但尚未设法使任何工作正常-MS Access选择按多个字段分组的前n个查询
VBA代码创建表:
Sub Create() Dim db As DAO.Database Set db = CurrentDb db.Execute "CREATE TABLE qry_REP_ErrorMargin" & _ "(TMID LONG, WeekCommencing DATE, ErrorMargin Double)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (1,42282,0)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (1,42289,2)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (3,42282,1)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (3,42289,1)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (8,42289,2)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (9,42282,0.333333333333333)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (9,42289,4)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (12,42282,0)" db.Execute "INSERT INTO qry_REP_ErrorMargin" & _ "(TMID, WeekCommencing, ErrorMargin) VALUES (12,42289,1.5)" End Sub
以下可能会做您想要的:
SELECT em.* FROM qry_REP_ErrorMargin as em WHERE em.TMID IN (SELECT TOP 3 TMID FROM qry_REP_ErrorMargin as em2 WHERE em2.WeekCommencing = em.WeekCommencing ORDER BY em2.ErrorMargin );
请注意,在平局的情况下,MS Access可能返回多于三行。如果您不希望重复,则在中添加一个id列ORDER BY以防止联系:
ORDER BY
ORDER BY em2.ErrorMargin, em2.TMID