我有一个名为“Calls”的表。表格的列组织为
CallCounter, AssignedEmpID, CompletedByEmpID
1 200 200
2 200 200
3 201 200
4 200 200
5 201 201
6 201 200
7 200 200
8 200 200
9 200 201
10 201 201
...
如何创建将返回以下数据的Select SQL查询。理想情况下,我想在1个查询中完成整个SQL查询。
Employee # Calls Assigned # Calls Completed
200 6 7
201 4 3
我尝试了以下查询
SELECT AssignedEmpID, COUNT(CallCounter) FROM CALLS
SELECT COUNT(*) FROM Calls
答案 0 :(得分:2)
首先,您需要定义员工列表。如果您没有union
表到employees
,则可以使用子查询和join
执行此操作。
然后你可以使用conditional aggregation
:
select t.empid,
sum(case when t.empid = c.AssignedEmpID then 1 else 0 end) AssignedCount,
sum(case when t.empid = c.CompletedByEmpID then 1 else 0 end) CompletedCount
from (select distinct AssignedEmpID as empid from calls
union select distinct CompletedByEmpID from calls) t
join calls c on t.empid in (c.AssignedEmpID, c.CompletedByEmpID)
group by t.empid
答案 1 :(得分:0)
我会使用union all
和group by
:
select EmpId, sum(assigned) as assigned, sum(completed) as completed
from ((select AssignedEmpID as EmpId, 1 as assigned, 0 as completed
from calls
) union all
(select CompletedByEmpID, 0, 1
from calls
)
) e
group by EmpId;
另一种方法是full outer join
:
select coalesce(a.EmpId, c.EmpId),
coalesce(assigned, 0) as assigned,
coalesce(completed, 0) as completed
from (select AssignedEmpID as EmpId, count(*) as assigned
from calls
group by AssignedEmpID
) a full outer join
(select CompletedByEmpID as EmpId, count(*) as completed
from calls
group by CompletedByEmpID
) c
on a.EmpId = c.EmpId;