select sum(c) from generate_series(1,:nitems) s
cross join lateral (select * from a where a=(s%1000) and b<=5000 order by a, b desc limit :nlimit) _;
