3

有两个表与此相关。工作和员工。这两个表的内容是员工的 EMPID NAME SALARY DID(部门 ID)和 PID EMPID HOURS from work on。我写的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

我一直在试图弄清楚为什么这段代码不会给我从事多个项目的员工。请帮我弄清楚我做错了什么。

4

3 回答 3

3

您的 group by 每个项目每个员工返回一行,根据定义,这永远不会超过 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
于 2012-11-14T20:50:34.927 回答
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 关联的所有记录与超过 1 个项目,并且主查询正在检查 empid 表中的 empid 是否在子查询的结果中。

于 2012-11-14T22:48:29.053 回答
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
于 2018-12-13T10:51:13.963 回答