select max(v.anno) as anno, max(r.numeropaginaregistroiva) + 1 as paginariepilogo from versamentoriepilogo r inner join versamento v on v.id = r.idversamento inner join tipoversamentolettera l on l.id = v.idtipoversamentolettera where v.dataemissione between [[dataemissionedal:dbdate]] and [[dataemissioneal:dbdate]] and extract(month from [[dataemissionedal:dbdate]]) = extract(month from [[dataemissioneal:dbdate]]) and l.idsezionale in (6,7) and v.numero > 0 and ( select count(*) from versamentoriepilogo r inner join versamento v on v.id = r.idversamento inner join tipoversamentolettera l on l.id = v.idtipoversamentolettera where v.dataemissione between [[dataemissionedal:dbdate]] and [[dataemissioneal:dbdate]] and l.idsezionale in (6,7) and v.numero > 0 and r.numeropaginaregistroiva = 0) = 0