如何按部门计算完成和待处理任务的数量

时间:2017-02-07 11:26:57

标签: sql sql-server sql-server-2008

我有下表。

表:部门

ID int
Name Varchar(50)

表:任务

Id int
ProjectId int,
TaskName varchar(50)
Status bit() -- 100 for complete else notComplete

表:用户

UserId int
DepId int
Name varchar(50),

表:TeamMember

Id int,
UserId int,
ProjectId int

我只想按部门统计完成和待处理的任务。这是我试过的:

select sub.Name,sub.result,count(*)
from (
    select tmm.userid,dp.Name,tm.id,tm.ActivityName,CASE ActualComplete WHEN 100 THEN 'done 100' ELSE 'In Complete' END as result 
    from MasterActivity tm
    inner join TeamMember_Master tmm on tmm.projectid=tm.projectid 
    inner join Users_Master us on us.UserId=tmm.userid
    inner join departments dp on us.DepartmentId=dp.id
) sub
group by sub.name,sub.result 

1 个答案:

答案 0 :(得分:0)

试试这样:

select dep.ID, dep.Name, sum(case when t.Status = 100 then 1 else 0 end) as Completed_Cnt, 
   sum(case when t.Status <> 100 then 1 else 0 end) as NotCompleted_Cnt 
from Task t
inner join TeamMember tm on tm.ProjectId = t.ProjectId
inner join [User] u on u.Id = tm.UserId
inner join Department dep on dep.Id = u.DepId
group by dep.Id, dep.Name

这应该有效(这是我的首要任务),但如果您没有提供样本数据和预期结果的最小示例,我们无法为您提供更多帮助。

请阅读此article,了解如何在SO上提问。