SQL员工在同一部门中搜索其他人

时间:2018-05-01 13:08:41

标签: sql sql-server teradata

我有一项业务规则,即员工无法从同一部门的员工处购买商品。我有两张桌子。一个是员工及其ID的列表:

   Emp_ID Emp_Name  Dept_ID
       1     John        1
       2      Bob        1
       3    Susie        2
       4     Jack        3
       5     Jill        3

他们购买的员工ID和员工ID表:

   Emp_ID  Bought_From_Emp_ID
       1                   2
       2                   3
       4                   5
       5                   1

我的预期输出是拥有两名员工的员工ID(或姓名),如果有人从同一部门购买了一件物品:

   Emp_ID  Bought_From_Emp_ID  Same_Dept_ID
       1                   2             1 --John and Bob are in Same Department (1)
       4                   5             3 --Jack and Jill are in Same Department (3)

我如何为数百万条记录执行此操作?从长远来看,我觉得这很简单,但我的思想还没有转向解决方案。

我正在使用Teradata,但如果有任何特定于SQL的答案,则可以使用MSSQL

2 个答案:

答案 0 :(得分:2)

DECLARE @emp TABLE
(
    emp_id INT,
    emp_name VARCHAR(20),
    dept_id INT
);
INSERT INTO @emp
(
    emp_id,
    emp_name,
    dept_id
)
VALUES
--Emp_ID Emp_Name  Dept_ID    
(1, 'John ', 1),
(2, 'Bob', 1),
(3, 'Susie', 2),
(4, 'Jack', 3),
(5, 'Jill', 3);

DECLARE @purch TABLE
(
    emp_id INT,
    Bought_From_Emp_ID INT
);
INSERT INTO @purch
(
    emp_id,
    Bought_From_Emp_ID
)
VALUES
(1, 2),
(2, 3),
(4, 5),
(5, 1);


SELECT e.emp_id,
       e1.emp_id AS Bought_From_Emp_ID,
       e.dept_id AS Same_Dept_ID
FROM @purch p
    JOIN @emp e
        ON p.emp_id = e.emp_id
    JOIN @emp e1
        ON p.Bought_From_Emp_ID = e1.emp_id
           AND e.dept_id = e1.dept_id
WHERE e1.emp_id <> e.emp_id;

答案 1 :(得分:1)

尝试此查询

SELECT purch.emp_id             AS EmpID, 
       purch.bought_from_emp_id AS BoughtFrom, 
       T1.dept_id               AS department 
FROM   purch 
       INNER JOIN emp T1 
               ON T1.emp_id = purch.emp_id 
       INNER JOIN emp T2 
               ON T2.emp_id = purch.bought_from_emp_id 
WHERE  t1.dept_id = t2.dept_id 

输出

+-------+------------+------------+
| EmpID | BoughtFrom | department |
+-------+------------+------------+
|     1 |          2 |          1 |
|     4 |          5 |          3 |
+-------+------------+------------+

演示:http://www.sqlfiddle.com/#!18/22746/1/0