this is my query SELECT `pf`.`id`, `me`.`id` as `user_id`, `me`.`email`, `me`.`username`, `me`.`name`, `me`.`mobile` as `phone`, SUM(pf.amount) as p_amount, @b := if(@rty != pf.extra_field1, @b + ts.amount, @b) as t_amount, @rty := pf.extra_field1 FROM (SELECT @b :=0 , @rty := 0 )as dummy CROSS JOIN`transaction_summary` `pf` LEFT JOIN `users` `me` ON `me`.`id` = `pf`.`user_id` LEFT JOIN `transaction_summary` `ts` ON `ts`.`id` = `pf`.`extra_field1` WHERE `pf`.`transaction_type` = 1 GROUP BY `pf`.`user_id`