select distinct
Patient_Ref_master.Dept_ID as 'dept',
Patient_Ref_master.Male_femal as 'Gender',
count(Patient_Ref_master.Pat_ID) as 'count'
from
Patient_Ref_master
left join
Patient_Master on Patient_Master.Pat_Code=Patient_Ref_master.Pat_ID
where
(Patient_Ref_master.Age > 16
and dbo.Patient_Master.Pat_Sex = 2
and Patient_Ref_master.creation_Date = '2013/08/02')
or
(Patient_Ref_master.Age > 16
and dbo.Patient_Master.Pat_Sex = 1
and Patient_Ref_master.creation_Date = '2013/08/02')
or
(Patient_Ref_master.Age >= 0
and Patient_Ref_master.Age <= 16
and dbo.Patient_Master.Pat_Sex = 2
and Patient_Ref_master.creation_Date = '2013/08/02')
or
(Patient_Ref_master.Age >= 0
and Patient_Ref_master.Age <= 16
and dbo.Patient_Master.Pat_Sex = 1
and Patient_Ref_master.creation_Date = '2013/08/02')
group by
Patient_Ref_master.Male_femal, Patient_Ref_master.Dept_ID
select distinct
Patient_Ref_master.Dept_ID