select year(vstdate) year,month(vstdate) month
,date(date_format(vstdate,'%Y-%m-01')) firstday
,last_day(vstdate) lastday
,if(month(vstdate) in (10,11,12),1
,if(month(vstdate) in(1,2,3),2
,if(month(vstdate) in(4,5,6),3
,if(month(vstdate) in(7,8,9),4,0)))) TriMonth
from ovst
where vstdate between '2012-10-1' and '2013-9-30'
group by month
order by year,month