我有以下两个表
表A
Name Location Group Value
July AAA A 1
Aug BBB B 2
Sep CCC C 3
Oct DDD D 4
Nov EEE E 5
表AA
Name Location Group Value1
July AAA A 6
Aug BBB B 7
Jan CCC C 8
Oct DDD D 9
Nov FFF F 10
我想要以下结果
Name Location Group Value Value1
July AAA A 1 6
Aug BBB B 2 7
Jan CCC C 8
Sep CCC C 3
Oct DDD D 4 9
Nov EEE E 5
Nov FFF F 10
到目前为止,我使用了以下查询,但我无法得到结果..
SELECT A.Name, A.Location, A.Gruppo, A.value, AA.value1
FROM A
Full Outer Join AA
ON A.LOCATION=AA.LOCATION
and
A.GRUPPO=AA.GRUPPO
and
A.name = AA.NAME
查询的结果如下
Name Location Gruppo value value 1
July AAA A 1 6
Aug BBB B 2 7
8
Oct DDD D 4 9
10
Sep CCC C 3
Nov EEE E 5
任何人都可以帮助我。
答案 0 :(得分:2)
你没有得到你所得到的结果的原因是你没有告诉查询为连接条件中的列选择哪个列不为空。
例如,如果行同时出现在A和AA中(或仅出现在A中),那么a.name
将不为空。但是,如果行仅出现在AA中,则a.name
将为空。在这种情况下,您希望它显示aa.name
,您可以使用COALESCE(或NVL):
WITH a AS (SELECT 'July' NAME, 'AAA' LOCATION, 'A' "GROUP", 1 VALUE FROM dual UNION ALL
SELECT 'Aug' NAME, 'BBB' LOCATION, 'B' "GROUP", 2 VALUE FROM dual UNION ALL
SELECT 'Sep' NAME, 'CCC' LOCATION, 'C' "GROUP", 3 VALUE FROM dual UNION ALL
SELECT 'Oct' NAME, 'DDD' LOCATION, 'D' "GROUP", 4 VALUE FROM dual UNION ALL
SELECT 'Nov' NAME, 'EEE' LOCATION, 'E' "GROUP", 5 VALUE FROM dual),
aa AS (SELECT 'July' NAME, 'AAA' LOCATION, 'A' "GROUP", 6 VALUE1 FROM dual UNION ALL
SELECT 'Aug' NAME, 'BBB' LOCATION, 'B' "GROUP", 7 VALUE1 FROM dual UNION ALL
SELECT 'Jan' NAME, 'CCC' LOCATION, 'C' "GROUP", 8 VALUE1 FROM dual UNION ALL
SELECT 'Oct' NAME, 'DDD' LOCATION, 'D' "GROUP", 9 VALUE1 FROM dual UNION ALL
SELECT 'Nov' NAME, 'FFF' LOCATION, 'F' "GROUP", 10 VALUE1 FROM dual)
-- end of mimicking your tables a and aa with data in them. See the SQL below:
SELECT coalesce(A.Name, aa.name) NAME,
coalesce(A.Location, aa.location) LOCATION,
COALESCE(A."GROUP", AA."GROUP") "GROUP",
A.value,
AA.value1
FROM A
Full Outer Join AA
ON A.LOCATION = AA.LOCATION
AND A."GROUP" = AA."GROUP"
and A.name = AA.NAME;
NAME LOCATION GROUP VALUE VALUE1
---- -------- ----- ---------- ----------
July AAA A 1 6
Aug BBB B 2 7
Jan CCC C 8
Oct DDD D 4 9
Nov FFF F 10
Sep CCC C 3
Nov EEE E 5
答案 1 :(得分:0)
您可以选择3次,其中一次使用内部,两次使用左边连接和排除。然后将它们全部合并到一个结果集中:
SELECT A.Name, A.Location, A.Gruppo, A.Value, AA.Value1
FROM A
inner join AA
ON A.Location = AA.Location
and A.Gruppo = AA.Gruppo
and A.Name = AA.Name
union all
SELECT A.Name, A.Location, A.Gruppo, A.Value, AA.Value1
FROM A
left outer join AA
ON A.Location = AA.Location
and A.Gruppo = AA.Gruppo
and A.Name = AA.Name
where Value1 is null
union all
SELECT AA.Name, AA.Location, AA.Gruppo, A.Value, AA.Value1
FROM AA
left outer join A
ON A.Location = AA.Location
and A.Gruppo = AA.Gruppo
and A.Name = AA.Name
where Value is null