此查询的目标是查找数据库中每个公司的平均员工数。以下是我目前查询的内容以及结果:
create view Totals as
((select distinct count(company_name) as TotalCompanies, company_name
from company
group by company_name)
union
(select distinct count(Lastname) as TotalEmps, company_name
from Works
group by company_name));
select avg(TotalCompanies) from Totals;
--RESULT:
AVG(TOTALCOMPANIES)
2.777777777778
虽然我确实得到了一个结果(所以我不相信有任何语法错误),根据我输入表格的实际数据,我不相信这个值是正确的。
我在视图创建中正在做什么,甚至让我到一个合适的点,我可以调用该视图的TotalCompanies字段的平均功能?我的意图是在视图中计算每个公司名称的所有员工,然后平均这些值......
对于FYI,我使用SQL for Oracle 11g R2,这是我的初始架构,我正在创建查询:
create table Employee(
Lastname varchar(10),
FirstName varchar(10),
MidInitial char(1),
gender char(1),
street varchar(10),
city varchar(10),
primary key(Lastname, FirstName, MidInitial));
create table company(
company_name varchar(20),
city varchar(10),
primary key(company_name));
create table Works(
Lastname varchar(10),
FirstName varchar(10),
MidInitial char(1),
company_name varchar(20),
salary numeric(8,2),
primary key(Lastname, FirstName, MidInitial, company_name),
foreign key(Lastname, FirstName, MidInitial) references Employee,
foreign key(company_name) references company);
感谢您的帮助!
答案 0 :(得分:0)
不考虑有关架构的问题,我相信以下内容可行:
Select
Avg(employeeCount)
From (
Select
company_name,
count(coalesce(w.LastName, w.FirstName, w.MidInitial)) employeeCount
From
company c
left outer join
works w
on c.company_name = w.company_name
Group By
company_name
) x
处理拥有0名员工的公司,以及将null作为其名称之一的人(我不确定Oracle是否在主键列中实际允许这样做,但定义似乎暗示了它),这有点棘手。
答案 1 :(得分:0)
创建一个视图,以存储每位员工的员工总数。
create view Totals as
(select count(*) as No_of_employees,company_name from Employee,Works
where Employee.Lastname = Works.Lastname and
Employee.FirstName = Works.FirstName and
Employee.MidInitial = Works.MidInitial
group by Works.company_name);
现在编写查询以查找每家公司的平均员工人数:
select avg(No_of_employees) from Totals;
这应该给你正确的答案。我用MySQL试过这个。请原谅我的任何错别字。