1

我有以下数据库设计:

Employees Table: EmployeeID, Name, OrgCode
Departments Table: OrgCode, DepartName
CompleteSurvey Table: ID, ParticipantID

我需要开发一个查询,该查询将显示一个表格,该表格显示所有部门的员工总数以及所有部门完成调查的参与者总数。

我可以通过以下查询找到所有部门的员工总数:

SELECT     COUNT(DISTINCT dbo.Employees.EmployeeID) AS [Total Number of Employees]
FROM         dbo.Departments INNER JOIN
                      dbo.Employees ON dbo.Departments.OrgCode = dbo.Employees.OrgCode CROSS JOIN
                      dbo.CompleteSurvey

然后,我可以通过以下查询找到所有部门的参与者总数:

SELECT     COUNT(DISTINCT dbo.CompleteSurvey.ID) AS [Total Number of Participants]
FROM         dbo.Departments INNER JOIN
                      dbo.Employees ON dbo.Departments.OrgCode = dbo.Employees.OrgCode INNER JOIN
                      dbo.CompleteSurvey ON dbo.Employees.EmployeeID = dbo.CompleteSurvey.RespondantID

但我应该只有一个查询。

例如,如果 A 部门有 100 名员工,参与者的数量是 50 / 100,B 部门有 80 名员工,参与者的数量是 30

查询应显示以下内容:

各部门员工总数=180

各部门总人数=80

所有这些的完成百分比 = 80/180 = 44%

那么该怎么做呢?

4

2 回答 2

1

我不知道 SQL Server,我希望 Oracle 解决方案也能提供帮助:

select e.employees, c.respondents, (c.respondents / e.employees) * 100 percentage
  from (select count(*) employees from employees) e,
       (select count(*) respondents from complete_survey) c
于 2012-05-16T06:09:14.410 回答
0

您不需要Department在这些计算中涉及该表:

SELECT
  TotalEmployees          = COUNT(*),
  TotalParticipants       = COUNT(s.ParticipantID),
  ParticipationPercentage = COUNT(s.ParticipantID) * 100.0 / COUNT(*)
FROM dbo.Employee e
  LEFT JOIN (SELECT DISTINCT ParticipantID FROM dbo.CompleteSurvey) s
    ON e.EmployeeID = s.ParticipantID
于 2012-05-17T07:58:49.433 回答