SQL选择多个coloumns每个计数somthing

时间:2016-05-20 09:31:53

标签: mysql sql count

显示几个带计数的coloumns时出现问题,这是我的表“Empo”:

idEmp    DeptA   DeptB  
----    ----    ----    
1       23      7      
2       42      23
3       23      11
4       23      17

我想计算idEmp的数量,以及每个Dept中'23'的次数得到这样的结果:

count(id) count(DeptA)   count(DeptB)  
----      ----           ----    
4         3              1

我还有另一张表“Rapport”

idRap   DeptA   bonnus 
----    ----    ----    
1       23      200      
2       42      23
3       23      346
4       77      44

我想得到DeptA的博纳斯总和

我如何在MySQL中执行此操作?

谢谢

3 个答案:

答案 0 :(得分:0)

我过去使用的方法是使用Count和Sum的组合。

select count(idEmp), 
sum(Case when DeptA = 23 Then 1 else 0 End), 
sum(Case when DeptB = 23 Then 1 else 0 End)
from tableX

编辑问题。 我会使用新案例的子选择来防止重复添加到原始计数。见下文。

select count(idEmp) as RecordCount, 
sum(Case when DeptA = 23 Then 1 else 0 End) as DeptA23Count, 
(select sum(bonnus) from Rapport where DeptA = 23) as BonnusForDeptA23,
sum(Case when DeptB = 23 Then 1 else 0 End) as DeptB23Count,
from tableX

或类似的东西取决于标准。

答案 1 :(得分:0)

尝试:

SELECT COUNT(idEmp) AS id,
  SUM(IF(DeptA = 23,1,0)) as COUNT_DeptA,
  SUM(IF(DeptB = 23,1,0)) as COUNT_Deptb
FROM youtTable;

答案 2 :(得分:0)

尝试以下查询: -

select (select count(id) from test) as countID,
(select count(DeptA) from test where DeptA=23) as CountDeptA,
(select count(DeptB) from test where DeptB=23) as CountDeptB