Declare @Cuenta int Select @cuenta = count(*) from (select idclie, max(fecha) from tabla where campo3='NO' group by idclie) A print @cuenta