sql to extract data for stats analysis