如何修改此查询以显示每个部门的员工总数和完成百分比?

时间:2012-06-24 06:10:55

标签: sql sql-server-2008-r2

我有以下数据库设计:

Employee Table: Username, Name, DivisionCode
Division Table: SapCode, DivisionShortcut
Courses Table: CourseID, CourseName, GroupID
Groups Table: GroupID, GroupName
Employee_Courses Table: EmployeeID, CourseID

我想出了以下查询,其中显示了每个部门的分部,课程和参与者总数:

SELECT     dbo.Divisions.DivisionShortcut, dbo.courses.CourseName, COUNT(dbo.employee_courses.courseId) AS [Total Number of Participants]
FROM         dbo.courses INNER JOIN
                      dbo.employee_courses ON dbo.courses.CourseID = dbo.employee_courses.courseId INNER JOIN
                      dbo.groups ON dbo.courses.GroupID = dbo.groups.ID RIGHT OUTER JOIN
                      dbo.employee AS employee_1 INNER JOIN
                      dbo.Divisions ON employee_1.DivisionCode = dbo.Divisions.SapCode ON dbo.employee_courses.employeeId = employee_1.Username
WHERE     (dbo.courses.GroupID = 1)
GROUP BY dbo.courses.CourseID, dbo.courses.CourseName, dbo.Divisions.DivisionShortcut

除了上面显示的内容外,我还要显示每个部门的员工总数以及每个部门的完成百分比。顺便说一下,完成百分比等于 (每个部门的参与者总数/每个部门的员工总数)

那怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用子查询将总员工数添加到部门的联接中。例如:

SELECT  d.DivisionShortcut
,       c.CourseName
,       d.EmployeeCount as DivisionEmployees
,       count(c.courseId) as CompletedCourses
,       100.0 * count(c.courseId) / d.EmployeeCount as PercentageCompleted
FROM    dbo.courses c
JOIN    dbo.employee_courses ec
ON      c.CourseID = ec.courseId
JOIN    dbo.employee e
ON      ec.employeeId = e.Username
JOIN    (
        select  d2.SapCode
        ,       d2.DivisionShortcut
        ,       count(e2.DivisionCode) as EmployeeCount
        from    dbo.Divisions d2
        JOIN    dbo.employee e2
        ON      d2.SapCode = e2.DivisionCode
        group by
                d2.SapCode
        ,       d2.DivisionShortcut
        ) d
ON      d.SapCode = e.DivisionCode
WHERE   c.GroupID = 1
GROUP BY 
        d.DivisionShortcut
,       d.EmployeeCount
,       c.CourseName