sql - Top 3 per group including 0 -
i have table want return top 3 records errormargin per week commencing in access 2010.
the problem i'm having 0 values being ignored , i'd see 1 record in case of ties tie take total number of records on 3.
the table have is:
nb: vba @ bottom of post create table.
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
the sql have @ moment is:
select t1.tmid, t1.weekcommencing, t1.errormargin, count(*) qry_rep_errormargin t1 inner join qry_rep_errormargin t2 on t1.errormargin <= t2.errormargin , t1.weekcommencing = t2.weekcommencing group t1.tmid, t1.weekcommencing, t1.errormargin having count(*) <= 3 order t1.weekcommencing, t1.errormargin
this returns following table, showing 2 records 5/10/2015 - there 2 further records 0 errormargin , i'd return 1 of well. doesn't matter which. tmid , weekcommencing fields make key field table.
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
i've had play around other solutions, haven't managed work yet - ms access select top n query grouped multiple fields
vba code create table:
sub create() dim db dao.database set db = currentdb db.execute "create table qry_rep_errormargin" & _ "(tmid long, weekcommencing date, errormargin double)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (1,42282,0)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (1,42289,2)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (3,42282,1)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (3,42289,1)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (8,42289,2)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (9,42282,0.333333333333333)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (9,42289,4)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (12,42282,0)" db.execute "insert qry_rep_errormargin" & _ "(tmid, weekcommencing, errormargin) values (12,42289,1.5)" end sub
the following may want:
select em.* qry_rep_errormargin em em.tmid in (select top 3 tmid qry_rep_errormargin em2 em2.weekcommencing = em.weekcommencing order em2.errormargin );
note in case of ties, ms access might return more 3 rows. not want duplicates, include id column in order by
prevent ties:
order em2.errormargin, em2.tmid
Comments
Post a Comment