$sql = " SELECT cg.client_id, goods_group.parent_goods_group_id, account_role.account_role_id, account_role.parent_role_id, account_role.dept, goods_group.name AS 'goods_group_name', account_role.`role_number`, account_role.`realname` AS 'role_name', account_role_parent.`role_number` AS 'parent_role_number', account_role_parent.`realname` AS 'parent_role_name', account_role.region_named, account_role.region_description, ccp_1.option AS 'custom_field_1', ccp_2.option AS 'custom_field_2', c.control, c.status, c.is_valid, c.number AS 'client_number', c.name AS 'client_name', region.name AS 'city', SUM( CASE WHEN 1 = 1 THEN (SELECT SUM(r2.purchase * g.ml_price / 10000) FROM report_day AS r2 WHERE r2.client_id = cg.client_id AND r2.goods_id = cg.goods_id AND r2.`account_role_id` = c.`charge_role_id` AND r2.end_time >= $reportDay AND r2.end_time <= $yesterdayEnd) ELSE 0 END ) AS 'sales_this_month', MAX( CASE WHEN 1 = 1 THEN (SELECT SUM(f.purchase) FROM `flow_day` AS f WHERE f.client_id = cg.client_id AND f.goods_id = cg.goods_id AND f.`operation_role_id` = c.`charge_role_id` AND f.timestamp >= $flowDay AND f.timestamp <= $yesterdayEnd) ELSE '' END ) AS 'max_flow_three_month' , CASE WHEN account_role.account_id = account_role_parent.account_id THEN 1 ELSE 0 END AS 'is_parent' FROM `client_goods2` AS cg LEFT JOIN `client` AS c ON cg.client_id = c.client_id LEFT JOIN `account_role` ON account_role.account_role_id = c.`charge_role_id` LEFT JOIN goods AS g ON g.goods_id = cg.goods_id LEFT JOIN `goods_group` ON goods_group.`goods_id` = cg.`goods_id` LEFT JOIN account_role AS account_role_parent ON account_role.parent_role_id = account_role_parent.account_role_id LEFT JOIN client_custom_option AS ccp_1 ON ccp_1.client_custom_option_id = c.custom_field_1 LEFT JOIN client_custom_option AS ccp_2 ON ccp_2.client_custom_option_id = c.custom_field_2 LEFT JOIN region ON region.`region_id` = c.city_id WHERE cg.goods_id IN ($goodsIds) AND cg.`is_valid` = 1 GROUP BY cg.`client_id` ; ";