create table t1 (userid int,username varchar(8),genger varchar(8),dept_id int)
insert into t1 select 1,'adam','male',1
union all select 2,'hellen','female',2
union all select 3,'larry','male',1
union all select 4,'kim','male',1
union all select 5,'bash','male',2
union all select 6,'tom','female',1
--select * from @t1
create table t2 (dept_id int,dept_name varchar(10))
insert into t2 select 1,'it'
union all select 2,'sales'
;with cte as
(
select b.dept_name,a.genger,count(*) 次数 from t1 a join t2 b on a.dept_id=b.dept_id
group by dept_name,genger
)
select dept_name,male= sum(case when genger='male' then 次数 else ''end),
female=sum(case when genger='female' then 次数 else '' end)
from cte
group by dept_name
---------------------
drop table t1
drop table t2
it 3 1
sales 1 1