select organisation, firstname, lastname, username count(case when csastatus = "completed" then 1 else null end) as completed, count(case when csastatus = "notstarted" then 1 else null end) as notstarted, count(case when csastatus = "inprogress" then 1 else null end) as inprogress, count(case when csastatus = "failed" then 1 else null end) as failed, count(case when csastatus = "refresherdue" then 1 else null end) as refresherdue, case when count(case when csastatus = "notstarted" then 1 else null end) = 0 and count(case when csastatus = "inprogress" then 1 else null end) = 0 and count(case when csastatus = "failed" then 1 else null end) = 0 and count(case when csastatus = "refresherdue" then 1 else null end) = 0 and count(case when csastatus = "completed" then 1 else null end) > 1 then "finished course" else "not finished course" end as coursestatus from tbl_trainingmatrix group by username order by coursestatus desc "completed": "218", "notstarted": "138", "inprogress": "10", "failed": "1", "refresherdue": "1"