Fix nitstats sql and improve tests