select r.id as restaurant_id, r.slug as restaurant_slug, sum(case when f.is_on_dnc_list = true then 1 else 0 end) as dnc_followers, round((sum(case when f.is_on_dnc_list = true then 1 else 0 end) * 100.0) / nullif(count(f.id), 0),2) as dnc_percentage_out_of_followers, sum(case when f.is_sms_unsubscribed = true then 1 else 0 end) as followers_with_is_sms_unsubscribed, round((sum(case when f.is_sms_unsubscribed = true then 1 else 0 end) * 100.0) / nullif(count(f.id), 0),2) as sms_unsubscribed_percentage_out_of_followers, count(f.id) as total_followers from restaurants r left join followers f on f.restaurant_id = r.id where r.status = 0 group by r.id, r.slug order by dnc_percentage_out_of_followers desc, total_followers desc Example export "restaurant_id","restaurant_slug","followers_with_is_on_dnc_list","dnc_percentage_out_of_followers", "followers_with_is_sms_unsubscribed", "sms_unsubscribed_percentage_out_of_followers 1,abcdefg,157813,35.27,5938,1.33,447398 2,hijklmn,155385,37.81,11728,2.85,410948