列出处理多个项目的员工姓名

时间:2012-11-14 20:37:05

标签: sql oracle11g

有两个表格与此相关。工作和员工。这两个表的内容是员工的EMPID NAME SALARY DID(部门ID)和工作的PID EMPID HOURS。我写的SQL是

select e.name, w.pid
from employee e, workon w
where e.empid = w.empid
group by e.name, w.pid, w.empid
having count (e.name) > 1
order by w.pid

我一直在试图找出为什么这段代码不会让我的员工在多个项目上工作。请帮我弄清楚我做错了什么。

3 个答案:

答案 0 :(得分:3)

你的小组每个项目每个员工返回一行,根据定义,这可能永远不会超过1行

下面的sql应该可以工作

警告:我不确定这将如何影响服务器使用的性能,风险自负

以下将为每个员工每个工作返回1行,但仅限于具有1个以上工作记录的员工(因此,如果员工有5个工作记录,您将获得5行具有相同的e.name,然后是5个不同的w.pid值)

select e.name, w.pid
from employee e, workon w
where e.empid = w.empid
and e.empid in (
select w.empid
from workon w -- there was a typo here originally
group by 1
having count (*) > 1
)
order by e.name, w.pid

答案 1 :(得分:1)

SELECT E.NAME, W.PID
from employee e inner join workon w on e.empid = w.empid
where e.empid in (select EMPID from workon GROUP BY EMPID HAVING COUNT(EMPID) > 1)

子查询使用与多个项目相关联的empid对所有记录进行计数,主查询正在检查empid表中的empid是否在子查询的结果中。

答案 2 :(得分:0)

您可以在下面的查询中尝试此操作。

在一个变量中,所有不同的计数部门均已从部门主表中获取。之后,仅选择那些计数与关联表中不同的链接部门计数匹配的员工。

CREATE TABLE employees
(
    employee_id int NOT NULL CONSTRAINT pk_employees PRIMARY KEY,
    employee_name nvarchar(128) NOT NULL CONSTRAINT uk_employees_employee_name UNIQUE
);

CREATE TABLE departments
(
    department_id int NOT NULL PRIMARY KEY,
    department_name nvarchar(128) NOT NULL CONSTRAINT uk_departments_department_name UNIQUE
);

CREATE TABLE department_employees
(
    department_id int NOT NULL CONSTRAINT fk_department_employees_departments REFERENCES departments(department_id),
    employee_id int NOT NULL CONSTRAINT fk_departement_employees_employees REFERENCES employees(employee_id),
    CONSTRAINT pk_deparment_employees PRIMARY KEY (department_id, employee_id)
)

INSERT INTO employees
VALUES (1, 'John Doe'), (2, 'Jane Doe'), (3, 'William Doe'), (4, 'Margaret Doe')

INSERT INTO departments
VALUES (1, 'Accounting'), (2, 'Humman Resources'), (3, 'Marketing')

INSERT INTO department_employees
VALUES 
    (1, 1), (2, 1), (3, 1), 
    (2, 2), (2, 3),
    (3, 3), (3, 4)

declare @distinctDeptCount int 
SET @DistinctDeptCount = (SELECT Count(Distinct department_id) FROM departments)
--SELECT @DistinctDeptCount

SELECT Distinct employees.employee_id, employee_name
from employees     
where employees.employee_id in (
select employee_id from department_employees GROUP BY employee_id HAVING COUNT(department_id) >= @distinctDeptCount
)

这是现场演示Emp. with all Department 输出如下所示

employee_id employee_name
1           John Doe