如何在子查询中使用外部查询中的列从另一个表中获取结果?

oymdgrw7  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(316)

我试图使用一个子查询从一个表中获得一个聚合结果,该子查询针对配置单元中另一个表的每一行。我知道hive不支持select子句中的子查询,所以我尝试在from子句中使用子查询,但似乎hive也不支持相关的子查询。
下面是一个示例:表a包含有日期列(d1和d2)和货币列以及其他列的账户交易数据,我要做的是得到表b中每个账户在日期d1和d2之间的汇率值总和(其中包含一年中每一天的汇率)。我试着这样做:

SELECT 
    account_no, currn, balance, 
    trans_date as d2, last_trans_date as d1, exchng_rt 
FROM 
    acc AS A, 
    (SELECT sum(rate) exchng_rt 
     FROM currency 
     WHERE curr_type = A.currn 
       AND banking_date BETWEEN A.d1 AND A.d2) AS B

这是一个示例,表a有如下帐户事务和日期:

account    balance    trans_date    last_trans_date    currency
abc        100        20-12-2016    20-11-2016          USD
abc        200        25-12-2016    20-12-2016          USD
def        500        15-11-2015    10-11-2015          AUD
def        600        20-11-2015    15-11-2015          AUD

表b是这样的:

curr_type     rate    banking_date
USD           50.9    01-01-2016
USD           50.2    02-01-2016
USD           50.5    03-01-2016
AUD           50.9    01-01-2016
AUD           50.2    02-01-2016
AUD           50.5    03-01-2016  and so on...

所以表中包含了每种货币的每日汇率

j9per5c4

j9per5c41#

我想你可以用它做你想做的事 JOIN 以及 GROUP BY :

SELECT a.account_no, a.currn, a.balance, a.trans_date as d2, a.last_trans_date as d1,
       SUM(rate) as exchng_rt 
FROM acc a LEFT JOIN
     currency c
     ON c.curr_type = a.currn and banking_date between A.d1 and A.d2
GROUP BY a.account_no, a.currn, a.balance, a.trans_date, a.last_trans_date;
oaxa6hgo

oaxa6hgo2#

应在连接两个表后指定筛选器,如下所示:

SELECT  A.account_no,
        A.currn, 
        A.balance,
        A.trans_date as d2,
        A.last_trans_date as d1, 
        B.exchng_rt 
FROM acc as A
JOIN (SELECT sum(rate) as exchng_rt,
         curr_type,
         banking_date
    FROM currency group by curr_type,
         banking_date ) as B
ON A.currn = curr_type 
WHERE B.banking_date between A.d1 and A.d2</code>

相关问题