SQL query fix for statistic