CREATE ALGORITHM = UNDEFINED DEFINER = `root`@`localhost` SQL SECURITY DEFINER VIEW `rpt_money_collected` AS select `c`.`id` AS `cemetery_id`, sum((case when ((`ia`.`psvc_fees` = 'pre') and (`ia`.`service_datetime` > ((curdate() - interval 1 year) - interval dayofmonth(curdate()) day)) and (`ia`.`service_datetime` <= (curdate() - interval dayofmonth(curdate()) day))) then ifnull(`ia`.`psvc_pre_charges`, 0) else 0 end)) AS `pre_need_year`, sum((case when ((`ia`.`psvc_fees` = 'at') and (`ia`.`service_datetime` > ((curdate() - interval 1 year) - interval dayofmonth(curdate()) day)) and (`ia`.`service_datetime` <= (curdate() - interval dayofmonth(curdate()) day))) then (ifnull(`ia`.`psvc_fee_amount`, 0) + ifnull(`ia`.`psvc_atneed_charges`, 0)) else 0 end)) AS `at_need_year`, sum((case when ((`ia`.`psvc_fees` = 'pre') and (`ia`.`service_datetime` > ((curdate() - interval 1 month) - interval dayofmonth(curdate()) day)) and (`ia`.`service_datetime` <= (curdate() - interval dayofmonth(curdate()) day))) then ifnull(`ia`.`psvc_pre_charges`, 0) else 0 end)) AS `pre_need_month`, sum((case when ((`ia`.`psvc_fees` = 'at') and (`ia`.`service_datetime` > ((curdate() - interval 1 month) - interval dayofmonth(curdate()) day)) and (`ia`.`service_datetime` <= (curdate() - interval dayofmonth(curdate()) day))) then (ifnull(`ia`.`psvc_fee_amount`, 0) + ifnull(`ia`.`psvc_atneed_charges`, 0)) else 0 end)) AS `at_need_month` from (`ia_fields` `ia` join `cemeteries` `c` ON ((`c`.`id` = `ia`.`cid`))) group by `c`.`id`