我很难编写hiveql连接

bq9c1y66  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(234)

我很确定这个问题已经问过了,但是我的搜索查询无法返回答案。我有两张table


**Table Online**

Col1   Col2    Score   |
a      b       1       |
a      c       2       |
a      d       3       |
f      e       4       |

**Table Offline**

Col1   Col2    Score   |
a      m       10      |
a      c       20      |
a      d       30      |
t      k       40      |

**Table Output**

Col1  Col2  Online.Score  Offline.Score    |
a     c     2             20               |    
a     d     3             30               |
a     b     1                              |
a     m                   10               |
2ledvvac

2ledvvac1#

你可以用一个 full join :

select coalesce(onl.col1, ofl.col1) as col1,
       coalesce(onl.col2, ofl.col2) as col2,
       onl.score, ofl.score
from (select onl.*
      from online onl
      where onl.col1 = 'a'
     ) onl full join
     (select ofl.*
      from offline ofl
      where ofl.col1 = 'a'
     ) ofl
     on onl.col1 = ofl.col1 and onl.col2 = ofl.col2;

过滤是很棘手的 full join ,这就是它使用子查询的原因。

ttcibm8c

ttcibm8c2#

使用下面的查询!

SELECT online.col1
    ,online.col2
    ,coalesce(online.score, 0) AS onlinescore
    ,coalesce(offlilne.score, 0) AS offlinescore
FROM online
INNER JOIN offline
    ON online.col1 = offline.col1
    AND online.col2 = offline.col2
UNION ALL
SELECT online.col1
    ,online.col2
    ,coalesce(online.score, 0) AS onlinescore
    ,'' AS offlinescore
FROM online
LEFT JOIN offline
    ON online.col1 = offline.col1
    AND online.col2 = offline.col2
WHERE offline.col1 IS NULL
UNION ALL
SELECT offline.col1
    ,offline.col2
    ,'' AS onlinescore
    ,coalesce(offline.score, 0) AS offlinescore
FROM offline
LEFT JOIN online
    ON online.col1 = offline.col1
    AND online.col2 = offline.col2
WHERE online.col1 IS NULL

相关问题