2014-12-09 47 views
2
全名

我正在寻找像输出:获取基于用户名2列

| BOOK |  ANALYST |   SUPERVISOR | 
|-------|----------------|--------------------| 
| BookA |   (null) |   Dani Sant | 
| BookB |   (null) | North Andre Miles | 
| BookC | Andrea Plus |  Andrea Plus | 
| BookD | Jeff Dron Math |  Jeff Dron Math | 
| BookE | Theo Phillip |  Julian Rhode | 

我所得到的是:

| BOOK |  ANALYST | SUPERVISOR | 
|-------|----------------|--------------| 
| BookA |   (null) | dani.sant | 
| BookB |   (null) | north.miles | 
| BookC | Andrea Plus | andrea.plus | 
| BookD | Jeff Dron Math | jeff.math | 
| BookE | Theo Phillip | julian.rhode | 

我可以做一个栏的加入,但当我尝试这两种方式时,结果并不像它应该显示的那样。感谢有关这方面的任何信息。

SQL Fiddle

MS SQL Server 2008的架构设置

CREATE TABLE books 
    (
    book varchar(10), 
    analyst varchar(100), 
    supervisor varchar(100) 
); 

INSERT INTO books (book, analyst, supervisor) 
VALUES 
('BookA', NULL, 'dani.sant'), 
('BookB', NULL, 'north.miles'), 
('BookC', 'andrea.plus', 'andrea.plus'), 
('BookD', 'jeff.math', 'jeff.math'), 
('BookE', 'theo.phil', 'julian.rhode'); 

CREATE TABLE names 
    (
    username varchar(100), 
    fullname varchar(500) 
); 

INSERT INTO names (username, fullname) 
VALUES 
('dani.sant', 'Dani Sant'), 
('north.miles', 'North Andre Miles'), 
('andrea.plus', 'Andrea Plus'), 
('jeff.math', 'Jeff Dron Math'), 
('theo.phil', 'Theo Phillip'), 
('julian.rhode', 'Julian Rhode'); 

查询1

SELECT 
    books.book AS Book, 
    names.fullname AS Analyst, 
    books.supervisor AS Supervisor 
FROM 
    books left join names on books.analyst = names.username 

Results

| BOOK |  ANALYST | SUPERVISOR | 
|-------|----------------|--------------| 
| BookA |   (null) | dani.sant | 
| BookB |   (null) | north.miles | 
| BookC | Andrea Plus | andrea.plus | 
| BookD | Jeff Dron Math | jeff.math | 
| BookE | Theo Phillip | julian.rhode | 

回答

2

你需要一个第二joinnames表,以获得上司的全名:

SELECT b.book AS Book, bn.fullname AS Analyst, 
     sn.fullname AS Supervisor 
FROM books b left join 
    names bn 
    on b.analyst = bn.username left join 
    names sn 
    on b.supervisor = sn.username; 
1

下面将提供你想要的输出。

SELECT 
     b.book AS Book, 
     n.fullname AS Analyst, 
     (SELECT fullname FROM names where username=b.Supervisor) AS Supervisor 
    FROM 
     books b left join names n on b.analyst = n.username