SQL处理表中的数据 - 使用哪种技术?

时间:2018-01-31 09:50:26

标签: sql sql-server subquery self-join

我想在ONE表中处理数据,这是这样的表:

这是我的表:

ID  Name    Role    WID
-----------------------
1   Flo     EMP     888
2   Jack    MIDMAN  888
3   Bison   BOSS    888

我想只获得一行并添加这样的老板信息:

ID  Name    Boss        WID 
---------------------------
1   Flo     Bison       888

我做了这个查询:

select
    ID,
    Name,
    (SELECT Name FROM Employee WHERE Role = 'BOSS' and  WID = 888) AS Boss,
    WID
    from Employee
where WID = 888
and Role <> 'BOSS' and Role <> 'MIDMAN'

还有其他更好/更清洁的方法吗?我试过自我加入但没有成功......

3 个答案:

答案 0 :(得分:1)

自我加入示例 -

select e1.id,e1.name,e2.name as boss,e1.wid
from Employee e1 inner join Employee e2
on e1.wid = e2.wid
and e1.role = 'EMP' and e2.role = 'BOSS'

答案 1 :(得分:1)

您可以将联接用作

select a.Name. b.Name as Boss, a.WID
from Employee a 
inner join Employee b on and a.WID = 888 and a.WID = b.WID 
      and b.role ='BOSS' and a.Role NOT IN (BOSS', 'MIDMAN')

答案 2 :(得分:0)

试试这个:

select [EMP].ID,
       [EMP].Name [Name],
       [BOSS].Name [Boss],
       [EMP].WID
from (
    select Name, 'EMP', WID from MY_TABLE where Role = 'EMP'
) as [EMP] join (
    select Name, 'BOSS', WID from MY_TABLE where Role = 'BOSS'
) as [BOSS] on [EMP].WID = [BOSS].WID