Try like this:-With Diabetes(person_id) as(select distinct person_id from(select count(*) as countperson,a.person_id,a.date_of_birth,(2008-year(a.date_of_birth)) as agefrom person ajoin diabetes_ b on a.person_id = b.person_idjoin patient_encounter c on a.person_id = b.person_id where year(c.create_timestamp) = '2008'group by a.person_id,a.date_of_birth)tmpwhere tmp.age >=18 and tmp.countperson >=2)select count(*), b.race,case when a.hga1cpercent<=7 then 1 when a.hga1cpercent>7 and a.hga1cpercent=9 then 2 when a.hga1cpercent>9 then 3end as GroupType,max(a.create_timestamp)from Diabetes tmpjoin diabetes_flwsheet_ a on tmp.person_id = a.person_idjoin person b on tmp.person_id = b.person_idgroup by b.race,case when a.hga1cpercent<=7 then 1 when a.hga1cpercent>7 and a.hga1cpercent=9 then 2 when a.hga1cpercent>9 then 3end