select dua.UARTERS_ID,dua.UARTERS_NAME ,sum(case when sex = '1' then 1 else 0 end) as Man ,sum(case when sex = '0' then 1 else 0 end) as Woman from dbo.DCAD_USER as du left join dbo.DCAD_UARTERS as dua on du.UARTERS_ID = dua.UARTERS_ID group by dua.UARTERS_ID,dua.UARTERS_NAME