【问题标题】:Get distinct values in union all in hive在配置单元中的联合中获取不同的值
【发布时间】:2014-12-19 07:53:04
【问题描述】:

我在 hive 中有一张桌子,看起来像这样

cust_id  prod_id timestamp
1        11      2011-01-01 03:30:23
2        22      2011-01-01 03:34:53
1        22      2011-01-01 04:21:03
2        33      2011-01-01 04:44:09
3        33      2011-01-01 04:54:49

以此类推。

对于每条记录,我想检查该客户在过去 24 小时内购买了多少独特产品,不包括当前交易。所以输出应该是这样的 -

1     0
2     0
1     1
2     1
3     0

我的 hive 查询看起来像这样

select * from(
select t1.cust_id, count(distinct t1.prod_id) as freq from temp_table t1
left outer join temp_table t2 on (t1.cust_id=t2.cust_id) 
where t1.timestamp>=t2.timestamp 
and unix_timestamp(t1.timestamp)-unix_timestamp(t2.timestamp) < 24*60*60
group by t1.cust_id
union all
select t.cust_id, 0 as freq from temp_table t2
)unioned;

【问题讨论】:

  • “排除当前交易”是什么意思?你的意思是“最近的交易”吗?

标签: mysql hadoop hive hiveql union-all


【解决方案1】:

只需获取过去 24 小时的所有行,按 custid 和 count(distinct productid) -1 作为输出进行分组。整体查询看起来像这样。

select cust_id, COUNT(distinct prod_id) - 1 from table_name where unix_timestamp(t1.timestamp)-unix_timestamp(t2.timestamp)

*我这里减1是为了排除用户最新的transactionid。 (希望这就是你的意思)

【讨论】:

    【解决方案2】:

    您可以加入一个派生表,其中包含每个客户/时间戳对在过去 24 小时内购买的不同产品数量。

    select t1.cust_id, t1.prod_id, t1.timestamp, t2.count_distinct_prod_id - 1
    from mytable t1
    join (
        select t2.cust_id, t2.timestamp, count(distinct t3.prod_id) count_distinct_prod_id
        from mytable t2
        join mytable t3 on t3.cust_id = t2.cust_id
        where unix_timestamp(t2.timestamp) - unix_timestamp(t3.timestamp) < 24*60*60
        group by t2.cust_id, t2.timestamp
    ) t2 on t1.cust_id = t2.cust_id and t1.timestamp = t2.timestamp
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多