2014-12-09 83 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