如何在SQL Server中连接表以获得预期的结果

时间:2015-08-28 07:53:41

标签: sql-server

表用户:

UID  |  NAME
------------
100  |  RAVI
101  |  Raju
102  |  Manju
103  |  Arun

表会话:

SID |    DATE   | TIME  | STrain_ID 
----------------------------------
1   | 1/1/2015  | 11:30 | 1
2   | 12/1/2015 | 12:30 | 2
3   | 25/1/2015 | 01:30 | 3
4   | 25/1/2015 | 02:30 | 4

表TRAINERS:

Train_ID | Primary   | secondarry   | other     | primID | secID | otherID
--------------------------------------------------------------------------
1        | RAVI      |              | Manju     | 100    |      |  102
2        |           | RAVI         |           |        | 100  |
3        |           |              | RAVI      |        |      |  100
4        |           | Manju        | Ravi      |        | 102  |  100

预期结果

SID | DATE      | TIME  | Train_ID | NAME | ROLE
-------------------------------------------------
1   | 1/1/2015  | 11:30 | 1        | RAVI |primary
1   | 1/1/2015  | 11:30 | 1        | Manju|other
2   | 12/1/2015 | 12:30 | 2        | RAVI |secondary
3   | 25/1/2015 | 01:30 | 3        | RAVI |other
4   | 25/1/2015 | 02:30 | 4        | Manju|secondary

2 个答案:

答案 0 :(得分:1)

检查以下代码。我看到了预期结果的模式,还有一行4-Train_ID,Ravi为"其他"角色。正如@JamesZ已经提到过你的设计,你也必须继续努力。

SELECT S.SID, S.DATE, S.TIME, S.STrain_ID AS Train_ID ,U.NAME, CASE WHEN T.[Primary] = U.NAME THEN 'Primary'
                                                        WHEN T.[Secondary]  = U.NAME THEN 'Secondary'
                                                        WHEN T.[Others]  = U.NAME THEN 'Others'  END AS [ROLE]
FROM #SESSION S
INNER JOIN #TRAINERS T ON S.STrain_ID = T.Train_ID
LEFT JOIN #USERS U ON (U.Name = T.[Primary])OR (U.Name = T.[Secondary]) OR (U.Name = T.Others)

如果有帮助,请将其标记为已解答。

答案 1 :(得分:0)

尝试以下查询,

select s.*,u.Name,t.src from [SESSION] s  join  
(select Train_ID,primID as usr,'primary' src from TRAINERS where primID is not null
union all
select Train_ID,secID, 'secondary' src from TRAINERS where secID is not null
union all
select Train_ID,otherID, 'others' src from TRAINERS where otherID is not null) t
 on s.[sid]=t.train_id join  USERS u on t.usr=u.[UID]