从查询中创建2个新列

时间:2013-04-19 10:37:38

标签: sql sql-server join

我正在与联盟和内部联盟作斗争。

我有两个看起来像这样的表:

USERS

-----------------------------------------
ID | fname | lname | div_1_id | div_2_id
-----------------------------------------
1    paul    smith     1         2
2    john    lip       2        null
3    kim     long      1         4

DIVISIONS

------------------
ID | name
------------------
1    estate
2    litigation
3    property
4    civil

DESIRED RESULT(sql query)

--------------------------------------------------
user.ID | fname | lname | div_1_name | div_2_name
--------------------------------------------------
  1        paul    smith     estate       litigation
  2        john    lip       litigation   
  3        kim     long      estate       civil

我想从MS sql查询创建一个新表,如上所示。

3 个答案:

答案 0 :(得分:1)

使用LEFT JOIN

SELECT u.ID, u.fname, u.lname
      , d1.name as div_1_name
      , d2.name as div_2_name 
FROM USERS u 
LEFT JOIN DIVISIONS d1 ON u.div_1_id = d1.ID 
LEFT JOIN DIVISIONS d2 ON u.div_2_id = d2.ID

See this SQLFiddle

答案 1 :(得分:1)

尝试使用子查询:

select a.ID, a.fname, a.lname,
    (select name from DIVISIONS b where b.id=a.div_1_id) div_1_name,
    (select name from DIVISIONS b where b.id=a.div_2_id) div_2_name
from 
USERS a

答案 2 :(得分:0)

使用INNER JOIN

SELECT Users.ID, Users.fname, Users.lname, Divisions.name,Div.name
FROM Users INNER JOIN Divisions ON Users.div_id_1 = Divisions.ID
INNER JOIN Divisions Div ON Users.div_id_1 = Div.ID -- Second join with Divisions Table with Alias.