SQL如何查找谁缺少项目

时间:2014-07-07 16:53:38

标签: sql sql-server

我有一个包含员工,员工项目,部门和部门项目的数据库 每个部门的每个员工都必须拥有特定的部门项目。

示例:部门Y有五个不同的部门项目a,b,c,d,每个员工必须在Employee项目表中包含这四个项目。但是,部门项目可能有2个,3个b,4个c和1个d,员工需要在Employee Items表中。

我尝试过不同的Sql但我无法得到正确的结果。
谢谢你的帮助。

我有以下表格。

员工表

EmpNum, Department, Gender
100      AAA          M
101      AAA          F
102      BBB          M
103      BBB          F
104      AAA          M
105      BBB          F

EmpProducts表

EmpNum,Item
100      A1
100      A1
100      A2
101      A2
102      B1
102      B3
103      B2
104      A1
104      A2
105      B1

产品

Deparment, Item, QtyM, QtyF
AAA         A1     2     1
AAA         A2     1     0
AAA         A3     1     1
BBB         B1     1     1
BBB         B2     2     3
BBB         B3     3     3

每个员工都需要拥有一定数量的产品,这些产品分配给我需要知道的员工部门,如果他们需要很少或很多。结果应该是。

100有性别和部门的正确项目,所以他不应该在结果中。

101  A2  1     She is 1 over the 0 she should have.
102  B2 -2
102  B3 -2
103  B1 -1
103  B2 -2
103  B2 -3
104  A1 -1
104  A3 -1
105  B2 -3
105  B3 -3

1 个答案:

答案 0 :(得分:1)

CREATE TABLE Departments (DepartmentId INT, DepartmentName VARCHAR(30))
CREATE TABLE DepartmentItems 
    (DepartmentItemId INT, DepartmentId INT, ItemName VARCHAR(30))
CREATE TABLE Employee
    (EmployeeId INT, DepartmentId INT, EmployeeName VARCHAR(100))
CREATE TABLE EmployeeItems (EmployeeId INT, DepartmentItemId INT)

INSERT Departments VALUES (1, 'Department A'), (2, 'Department B')
-- Depart A has three items
INSERT DepartmentItems VALUES
    (1, 1, 'Item A'), (2, 1, 'Item B'), (3, 1, 'Item C')
-- Department B has two items
INSERT DepartmentItems VALUES (4, 2, 'Item D'), (5, 2, 'Item E')

-- Two employees
INSERT Employee VALUES (1, 1, 'Kim'), (2, 2, 'Tom')

-- Kim's items
INSERT EmployeeItems VALUES (1, 1), (1, 2) -- Missing Item C from Department A..

-- Tom's items
INSERT EmployeeItems VALUES (2, 4) -- Missing Item E from Department B

-- Who is missing an item..
SELECT d.*, di.*, e.*
FROM Departments d
INNER JOIN DepartmentItems di
    ON di.[DepartmentId] = d.[DepartmentId]
INNER JOIN Employee e
    ON e.[DepartmentId] = d.[DepartmentId]
LEFT JOIN EmployeeItems ei
    ON ei.[EmployeeId] = e.[EmployeeId]
    AND ei.[DepartmentItemId] = di.[DepartmentItemId]
WHERE ei.[DepartmentItemId] IS NULL

enter image description here