具有由同一列分组的多个计数条件的MySQL查询

时间:2015-07-01 05:25:24

标签: mysql sql count

我不熟悉使用group by

的MySQL查询

我有这些表格:

  • 用户,其中包含以下列: useridpositiondept_idstatus
  • 部门包含以下列: dept_idname

我想要一个查询来计算位置为ojt,subcon的所有用户, 其状态在所有部门都已重新签署

所以我有一张看起来像这样的表:

SEDC dept:
ojt users count: 13
subcon users count: 32
resigned users count: 2


HR dept:
ojt users count: 2
subcon users count: 3
resigned users count: 1

Finance dept:
ojt users count: 4
subcon users count: 6
resigned users count: 1

3 个答案:

答案 0 :(得分:0)

SELECT d.dept_id,u.position,count(userid) AS count
FROM user u INNER JOIN department d
ON u.dept_id = d.dept.id AND u.status = 'resigned'
GROUP BY d.dept_id,u.position

答案 1 :(得分:0)

尝试此查询

select a.nam,case when position='ojt' then acount else o end as ojtuser
case when position='subcon' then acount else o end as subconuser
regincount 
  from department a
join(
select dept_id,Position,Count(*) acount from user
group by Dept_id,Position)b on a.dept_id=b.dept_id
join(
select dept_id,Count(*) regincount from user status=resigned
group by dept_id)c on a.dept_id=c.dept_id

答案 2 :(得分:0)

我尝试了这个查询,它对我有用:

SELECT d.departmentname dept, 
       sum(m.position = "subcon") subcon,   
       sum(m.position = "ojt") ojt,     
       sum(m.status = 'h') hr_intra
from user m
right join department d
on m.department_id = d.id
group by d.id