select Request_at as Day,round((max(counter)*1.0/count(Request_at)),2) as 'Cancellation Rate' from ( select Id,Status,Request_at, @counter:=if(@curDate=Request_at and Status <> 'completed',@counter+1,0) as temp_c,# same day @counter:=if(@curDate<>Request_at and Status <>'completed',1, @counter) as counter,# different day @curDate:=Request_at as curDate from (select * from Trips left join Users on Client_Id=Users_Id where Banned<>'Yes' and request_at >= '2013-10-01' and request_at <= '2013-10-03' order by Request_at) as temp_t, (select @count:=0,@curDate:='') as params ) as temp_tt group by Request_at
附
use test;
create table Trips(Id int auto_increment primary key,Client_Id int,Driver_Id int,City_Id int,Status varchar(50),Request_at date);
create table Users(Users_Id int auto_increment primary key,Banned varchar(10),Role varchar(20));
alter table Users modify column Users_Id int;#丢弃自增
insert into trips(Client_Id,Driver_Id,City_Id,Status,Request_at) values(1,10,1,'completed','2013-10-01'),(2,11,1,'cancelled_by_driver','2013-10-01'),(3,12,6,'completed','2013-10-01'),(4,13,6,'cancelled_by_client','2013-10-01'),(1,10,1,'completed','2013-10-02'),(2,11,6,'completed','2013-10-02'),(3,12,6,'completed','2013-10-02'),(2,12,12,'completed','2013-10-03'),(3,10,12,'completed','2013-10-03'),(4,13,12,'cancelled_by_driver','2013-10-03');
insert into Users(Users_Id,Banned,Role) values(1,' No','client'),(2,'Yes','client'),(3,' No','client'),(4,' No','client'),(10,'No','driver'),(11,'No','driver'),(12,'No','driver'),(13,'No','driver');