【问题标题】:Hive: error calculating SUM then MAX of grouped itemsHive:错误计算 SUM 然后 MAX 分组项目
【发布时间】:2018-07-11 11:37:00
【问题描述】:

我想运行一个查询来计算每张信用卡每个月的最大支出金额。对于每张信用卡,我需要计算每个月花费的金额。我有一张包含信用卡交易的表格credit_transact

processdate timestamp   ""
cardno_hash string  ""
amount  int ""
year    int ""
month   int ""

虚构的样本数据:

card    year    month    amount
a123    2016    12       23160
a123    2016    10       287
c123    2016    11       5503
c123    2016    11       4206

我想要:

card    year    month    amount
a123    2016    12       23160
c123    2016    11       9709

一个重要的事情是年和月是分区列。

我尝试过如下子查询:

USE credit_card_db;
SELECT sum_amount_transact.cardno_hash, sum_amount_transact.year, sum_amount_transact.month, MAX(sum_amount_transact.sum_amount)
FROM
(
  SELECT cardno_hash, year, month, SUM(amount) AS sum_amount FROM credit_transact
  GROUP BY cardno_hash, year, month
) AS sum_amount_transact
GROUP BY sum_amount_transact.cardno_hash, sum_amount_transact.year;

但是,显示以下错误:

java.lang.Exception: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: SemanticException Line 0:-1 Invalid column reference 'month'

以下子查询运行良好并按预期返回结果:

SELECT cardno_hash, year, month, SUM(amount) AS sum_amount FROM credit_transact
  GROUP BY cardno_hash, year, month

结果是:

card    year    month    amount
a123    2016    12       23160
a123    2016    10       287
c123    2016    11       9709

如果有人能帮助解决这个问题,我们将不胜感激。

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。如有必要,您可以编造合理的数据。
  • 抱歉,我不能对数据进行采样,因为数据是机密的。
  • 我相信月是 Hive 的保留关键字。您是否尝试将列命名为其他名称?
  • 我运行了运行良好的子查询,所以我认为不太可能是这种情况。我也检查了保留关键字列表,但它在非保留列中。
  • 您为什么不希望在第 10 个月出现您想要的结果?这是故意的吗?

标签: sql hive hiveql


【解决方案1】:

我不太清楚你真正想要什么,但我很确定你想要row_number()。我想你想要每年最多的月份:

SELECT ct.*
FROM (SELECT cardno_hash, year, month, SUM(amount) AS sum_amount,
             ROW_NUMBER() OVER (PARTITION BY cardno_hash, year ORDER BY SUM(amount) DESC) as seqnum
      FROM credit_transact
      GROUP BY cardno_hash, year, month
     ) ct
WHERE seqnum = 1;

【讨论】:

  • 我已编辑问题以包含示例数据,希望对您有所帮助
  • @LongLe 。 . .这个查询应该做你想做的事。
  • ROW_NUMBER() OVER (PARTITION BY cardno_hash, year ORDER BY SUM(amount) DESC) as seqnum这个我不太懂
  • @LongLe 。 . .你可以在网上找到很多资源。 . . dwgeek.com/hadoop-hive-analytic-functions-examples.html.
猜你喜欢
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-05
  • 2021-11-22
相关资源
最近更新 更多