【问题标题】:how to use columns from outer query in subquery to get result from another table?如何在子查询中使用外部查询中的列从另一个表中获取结果?
【发布时间】:2018-01-22 11:34:52
【问题描述】:

我正在尝试使用表中的子查询针对 hive 中另一个表的每一行来获取聚合结果。我知道 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...

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

【问题讨论】:

  • 编辑您的问题并提供示例数据和所需结果。

标签: sql hadoop hive hiveql


【解决方案1】:

我认为你可以使用JOINGROUP 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;

【讨论】:

  • 不能真正使用 group by,因为该表包含每个帐号的多个条目。我想分别获取每个交易条目或行的汇率
  • @Atif 。 . .有多个 group by 键,所以这应该不是问题。如果您有主键,请将其也放入group by
【解决方案2】:

您应该在连接两个表后指定过滤器,如下所示:

选择 A.account_no,
        A.currn,
        平衡,
        A.trans_date 为 d2,
        A.last_trans_date 为 d1,
        B.exchng_rt
FROM acc as A
JOIN (SELECT sum(rate) as exchng_rt,
         curr_type,
         银行日期
    FROM 货币组 by curr_type,
         银行日期)作为B
ON A.currn = curr_type
WHERE B.banking_date 在 A.d1 和 A.d2 之间

【讨论】:

  • 该组不会给出所需的结果,因为货币表每天都有记录,我想获得指定时期之间的汇率
  • banking_date 不等于一天吗?子查询按银行日期分组,外部查询按同一字段过滤。我在这里错过了什么?
猜你喜欢
  • 2023-03-23
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
相关资源
最近更新 更多