带复合键的T-SQL多外连接

时间:2013-07-17 13:16:46

标签: sql-server tsql join outer-join

我有两个源视图:

View1

-----------------------------------------------------
|  UserId  |  RoleId  |  Total1 (calculated value)  |
-----------------------------------------------------
|    1     |    21    |            9                |
-----------------------------------------------------
|    1     |    22    |            5                |
-----------------------------------------------------
|    2     |    21    |            7                |
-----------------------------------------------------
|    4     |    23    |            4                |
-----------------------------------------------------

View2

-----------------------------------------------------
|  UserId  |  RoleId  |  Total2 (calculated value)  |
-----------------------------------------------------
|    1     |    21    |            2                |
-----------------------------------------------------
|    1     |    24    |            1                |
-----------------------------------------------------
|    3     |    21    |            3                |
-----------------------------------------------------
|    4     |    21    |            4                |
-----------------------------------------------------

首选输出基于UserId和RoleId相等:

---------------------------------------------
|  UserId  |  RoleId  |  Total1  |  Total2  |
---------------------------------------------
|    1     |    21    |     9    |    2     |
---------------------------------------------
|    1     |    22    |     5    |   NULL   |
---------------------------------------------
|    1     |    24    |    NULL  |    1     |
---------------------------------------------
|    2     |    21    |     7    |   NULL   |
---------------------------------------------
|    3     |    21    |    NULL  |    3     |
---------------------------------------------
|   ...    |    ...   |    ...   |   ...    |

据我所知,我应该使用某种类型的OUTER JOIN - 但是如何?

2 个答案:

答案 0 :(得分:3)

SELECT
  ISNULL(v1.UserID,v2.UserID) as UserID,
  ISNULL(v1.RoleID,v2.RoleID) as RoleID,
  v1.Total1 ,
  v2.Total2
FROM view1 v1
FULL OUTER JOIN view2 v2
 ON v1.UserID = v2.UserID
 AND v1.RoleID = v2.RoleID

答案 1 :(得分:2)

假设每个表只有一个匹配的行,您可以使用FULL OUTER JOIN

SELECT COALESCE(v1.UserId, v2.UserId) AS UserId,
    COALESCE(v1.RoleId, v2.RoleId) AS RoleId,
    v1.Total1
    v2.Total2
FROM View1 v1
FULL OUTER JOIN View2 v2 ON v1.UserId = v2.UserId AND v1.RoleId = v2.RoleId

或者,您可以使用UNIONSUM结果,如果每个表的行都是非唯一的,并且连接会产生重复,则会非常有用:

SELECT UserId, RoleId, SUM(Total1) AS Total1, SUM(Total2) AS Total2
FROM
(
    SELECT UserId, RoleId, Total1, NULL AS Total2
    FROM View1
    UNION ALL
    SELECT UserId, RoleId, NULL AS Total1, Total2
    FROM View2
) Combined
GROUP BY UserId, RoleId