【问题标题】:Count the number of transactions per month for an individual group by date Hive按日期 Hive 计算单个组每月的事务数
【发布时间】:2020-07-26 11:28:57
【问题描述】:

我有一张客户交易表,其中客户购买的每件商品都存储为一行。因此,对于单个事务,表中可以有多行。我有另一个名为 visit_date 的列。 有一个名为 cal_month_nbr 的类别列,其范围为 1 到 12,具体取决于发生交易的月份。

数据如下所示

Id          visit_date     Cal_month_nbr
----        ------          ------
1           01/01/2020      1
1           01/02/2020      1
1           01/01/2020      1
2           02/01/2020      2
1           02/01/2020      2
1           03/01/2020      3
3           03/01/2020      3

首先 我想知道客户每月使用他们的 visit_date 访问多少次 即我想要低于输出

id    cal_month_nbr       visit_per_month
---        ---------     ----
1           1             2
1           2             1
1           3             1
2           2             1
3           3             1

每个 id 的平均访问频率是多少 IE。

id            Avg_freq_per_month
----          -------------
1              1.33
2              1
3              1

我尝试了以下查询,但它将每个项目计为一个事务

select avg(count_e) as num_visits_per_month,individual_id
from
(
    select r.individual_id, cal_month_nbr, count(*) as count_e
 from 
  ww_customer_dl_secure.cust_scan 
         GROUP  by 
         r.individual_id, cal_month_nbr
         order by count_e desc
         ) as t
         group by individual_id

如果有任何帮助、指导或建议,我将不胜感激

【问题讨论】:

  • id 1 的 1.33 是如何计算的?三个月内有五次访问,对我来说似乎是 1.67。
  • @GordonLinoff 表中的每一行都不是一次访问。每个条目都是为交易购买的物品。因此,对于 id 1,相同的 visit_date 即 2020 年 1 月 1 日在表中出现两次,这只是 1 笔交易,但购买了两件商品

标签: sql hive hiveql data-lake


【解决方案1】:

您可以将总访问次数除以月数:

select individual_id,
       count(*) / count(distinct cal_month_nbr)
from  ww_customer_dl_secure.cust_scan c
group by individual_id;

如果你想要每月的平均天数,那么:

select individual_id,
       count(distinct visit_date) / count(distinct cal_month_nbr)
from  ww_customer_dl_secure.cust_scan c
group by individual_id;

实际上,Hive 在计算count(distinct) 时可能效率不高,因此多级聚合可能会更快:

select individual_id, avg(num_visit_days)
from (select individual_id, cal_month_nbr, count(*) as num_visit_days
      from (select distinct individual_id, visit_date, cal_month_nbr
            from ww_customer_dl_secure.cust_scan c
           ) iv 
      group by individual_id, cal_month_nbr
     ) ic
group by individual_id;

【讨论】:

  • 如果每一行都是唯一的事务,则上述 Hive 查询有效,但一次访问可以有多行,因此 visit_date 告诉我们对于 id 1,总共有 4 个事务或 4 次访问跨度>
  • @krishnakoti 。 . .根据您的问题和示例数据,您似乎在计算不同的日期,而不是访问次数。
猜你喜欢
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多