1

我需要加入两个表并得到如下输出

T1

S    B   C   P
---  --  --  --
ABC  B1  C1  10
ABC  B2  C2  11
ABC  B3  C3  12

T2

S    B   C   P
---  --  --  --
ABC  B1  C1  12
ABC  B2  C2  13
ABC  B5  C5  14

我需要以下输出

S    B   C   P1  P2
---  --  --  --  --
ABC  B1  C1  10  12
ABC  B2  C2  11  13
ABC  B3  C3  12  0
ABC  B5  C5  0   14

请注意:我使用的是 Microsoft Access,而 Access SQL 不直接支持 FULL OUTER JOIN 查询。

4

3 回答 3

3

您可以模拟 FULL OUTER JOIN:

SELECT 
    T1.S, T1.B, T1.C, T1.P AS P1, IIF(ISNULL(T2.P), 0, T2.P) AS P2 
FROM
    T1 LEFT JOIN
    T2 ON (T1.S = T2.S AND T1.B = T2.B AND T1.C = T2.C)
UNION ALL
SELECT 
    T2.S, T2.B, T2.C, IIF(ISNULL(T1.P), 0, T1.P) AS P1, T2.P AS P2 
FROM
    T2 LEFT JOIN
    T1 ON (T1.S = T2.S AND T1.B = T2.B AND T1.C = T2.C)
WHERE T1.S IS NULL
于 2013-11-14T11:44:45.247 回答
1
SELECT s,
       b,
       c,
       SUM(temp_p1) as p1,
       SUM(temp_p2) as p2
  FROM (
         SELECT t1.s, 
                t1.b, 
                t1.c, 
                t1.p as temp_p1, 
                0 as temp_p2 
           FROM t1
      UNION ALL
         SELECT t2.s, 
                t2.b, 
                t2.c, 
                0 as temp_p1, 
                t2.p as temp_p2 
           FROM t2
       )
GROUP BY s,
         b,
         c
于 2013-11-14T12:25:11.470 回答
0
SELECT 
    T1.S, T1.B, T1.C, T1.P P1, T2.P P2 
FROM
    T1 left outer JOIN
    T2 ON (T1.S = T2.S AND T1.B = T2.B AND T1.C = T2.C)
UNION 
SELECT 
    T2.S, T2.B, T2.C, T1.P P1, T2.P P2 
FROM
    T2 LEFT outer JOIN
    T1 ON (T1.S = T2.S AND T1.B = T2.B AND T1.C = T2.C)
WHERE T1.S IS NULL
于 2013-11-14T12:13:19.250 回答