我需要连接两个表并获得如下输出
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查询。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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