Fix bug in sql for stats