0

我有两个源视图:

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 AND 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 - 但是如何?

4

2 回答 2

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
于 2013-07-17T13:23:52.757 回答
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

或者,您可以使用 aUNIONSUM结果,如果每个表的行都不唯一并且连接会产生重复,则特别有用:

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
于 2013-07-17T13:25:05.810 回答