如何使用依赖于现有列的额外列进行选择

时间:2013-12-19 16:12:59

标签: sql sql-server-2008

举个例子:

select * from table

得到了

ID | NAME | MAIL             | BOSS_ID |
1  | Mike | mike@mike.com    | 2       |
2  | Josh | josh@hotmail.com | null    |

我真正想做的是让SELECT语句(不知何故?)显示另外两列,如:

ID | NAME | MAIL             | BOSS_ID | BOSS_NAME | BOSS_MAIL
1  | Mike | mike@dfsfs.com   | 2       | Josh      | josh@dsa.com
2  | Josh | josh@dfsa.com    | null    | null      | null

我知道它看起来很傻,但我确实被要求做的...... 所有提示都非常值得赞赏!

2 个答案:

答案 0 :(得分:3)

您可以在IDBOSS_ID上对表格进行外部联接。

SQL Fiddle

MS SQL Server 2012架构设置

create table YourTable
(
  ID int,
  Name varchar(10),
  Mail varchar(20),
  BOSS_ID int
)
insert into YourTable values
(1  , 'Mike' , 'mike@mike.com'    , 2),
(2  , 'Josh' , 'josh@hotmail.com' , null)

查询1

select T1.ID, 
       T1.Name,
       T1.Mail,
       T2.Name as BossName,
       T2.Mail as BossMail
from YourTable as T1
  left outer join YourTable as T2
    on T1.BOSS_ID = T2.ID

<强> Results

| ID | NAME |             MAIL | BOSSNAME |         BOSSMAIL |
|----|------|------------------|----------|------------------|
|  1 | Mike |    mike@mike.com |     Josh | josh@hotmail.com |
|  2 | Josh | josh@hotmail.com |   (null) |           (null) |

答案 1 :(得分:0)

您无法选择不存在的列。您需要添加它们。你会想要一个像这样的ALTER TABLE语句:

ALTER TABLE yourtable ADD BOSS_NAME VARCHAR( 255 )