如何在表格中查找同事ID

时间:2019-05-31 07:40:26

标签: sql

我有一张表作为Employee,有两列Id和Branch。我必须在不使用子查询的情况下从表中找到其同名ID(除了他自己的ID)。

Id      Branch
==============
1       Delhi
2       Mumbai
3       Delhi
4       Delhi
5       Mumbai
6       Mumbai

如果我输入例如3,那么我的答案必须是1和4。

3 个答案:

答案 0 :(得分:1)

没有子查询意味着具有自连接:

select tt.* 
from tablename t inner join tablename tt 
on t.Branch = tt.Branch and tt.id <> t.id
where t.id = 3

请参见demo

答案 1 :(得分:0)

使用自我加入

  select t2.id from table_name t1 
  join table_name t2 on t1.Branch=t2.Branch
  where t1.id=3 and t2.id!=3

为了便于数据准备,我在下面使用了CTE版本并显示结果

 with cte as
(

select 1 as id, 'Delhi' as b
union all
select 2,    'Mumbai'
union all
select 3    ,  'Delhi'
union all
select 4  ,     'Delhi'

) select t2.id from cte t1 join cte t2 on t1.b=t2.b
  where t1.id=3 and t2.id!=3

demo link

这是输出

id
1
4

答案 2 :(得分:0)

此查询应为您提供答案:

SELECT  E1.Id
FROM    Employee E1
INNER
JOIN    Employee E2
        ON E1.[Branch] = E2.[Branch]
WHERE   E2.Id = 3
AND     E1.Id <> 3

通过Employee然后将Branch表连接到自身上来工作,

  • WHERE E2.Id = 3-员工的ID号为3
  • AND E1.Id <> 3-排除原始 Employee表中Id为3
  • 的任何记录

这是我用来在SQL Server中创建测试数据的脚本,用于验证查询:

CREATE TABLE [Employee]
( 
    [Id] INT,
    [Branch] NVARCHAR(10)
)

INSERT
INTO    [Employee]
        (
            Id,
            [Branch]
        )
VALUES  (1, 'Delhi'),
        (2, 'Mumbai'),
        (3, 'Delhi'),
        (4, 'Delhi'),
        (5, 'Mumbai'),
        (6, 'Mumbai')