SELECT员工已完成任务的数量

时间:2014-12-27 10:20:58

标签: sql select group-by sum pivot

如何在SQL中执行以下操作:

“选择列表标记所有任务的所有emps”.................................

EmpId  EmpName
------ --------
1        tom
2        jerry
3        jack


taskId EmpID    mark
------ -----   ------
1       1        5
2       3        0
3       1        10
4       2        5
5       2        10
6       3        5
7       3        5

结果:

EmpName  0       5       10    sum
------ -----   ------  ------  ----
tom      0       1        1     2
jerry    0       1        1     2
jack     1       2        0     3

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT e.EmpId, e.EmpName, 
       SUM(CASE WHEN t.mark = 0 THEN 1 ELSE 0 END) AS 0Mark, 
       SUM(CASE WHEN t.mark = 5 THEN 1 ELSE 0 END) AS 5Mark, 
       SUM(CASE WHEN t.mark = 10 THEN 1 ELSE 0 END) AS 10Mark, 
       COUNT(1) AS TotalMark
FROM employee e 
INNER JOIN task t ON e.EmpId = t.EmpId 
GROUP BY e.EmpId, e.EmpName;

答案 1 :(得分:-1)

select
   e.empname,
   (select count(*) from tasks t where e.empid=t.empid and mark=0) as mark0,
   (select count(*) from tasks t where e.empid=t.empid and mark=5) as mark5,
   (select count(*) from tasks t where e.empid=t.empid and mark=10) as mark10,
   (select count(*) from tasks t where e.empid=t.empid) as marksum        
from       
   employees e

答案 2 :(得分:-1)

这取决于您的数据库引擎 - 谷歌“Pivot SQL”+您的数据库引擎(例如“pivot SQL MySQL”)。

数据透视功能意味着您可以将“标记”列中的值转换为列标题,因此,如果您的标记范围为0到100,则每个值都会获得一列,而无需创建子查询。

如果您的数据库引擎不支持pivot,您可能需要对结果集中的列进行硬编码,如@LajosVeres所示。我会添加一个“catch-all”子查询,所以如果你的数据发生了变化,你就不会得到不合逻辑的结果,如下所示:

select
   e.empname,
   (select count(*) from tasks t where e.empid=t.empid and mark=0) as mark0,
   (select count(*) from tasks t where e.empid=t.empid and mark=5) as mark5,
   (select count(*) from tasks t where e.empid=t.empid and mark=10) as mark10,
   (select count(*) from tasks t where e.empid=t.empid and mark not in (0, 5, 10)) as otherMarks,
   (select count(*) from tasks t where e.empid=t.empid) as marksum        
from       
   employees e