研究Hive SQL 完成以下统计任务,写出统计sql
CREATE TABLE t_order
(ord_id
bigint,//订单号ord_amount
bigint,//订单金额cust_id
bigint,//客户idord_time
string) //订单时间:格式如2018-01-01 00:00:00
PARTITIONED BY (dt
string)//日期分区,格式20180101
1、统计用户月复购率,用户复购率定义:在上月有订单记录的用户,在本月仍然订单记录的用户,占上月有订单记录的用户的比例。
2、假设表中有2018年1-3月每一天的交易金额,统计1-3月每一个用户每天当月累计到当日的交易金额
select sum(if(t2.cust_id is not null, 1, 0)) / count(1) from (
select distinct cust_id from t_order o where o.ord_time>='2018-01-01' and o.ord_time < '2018-02-01'
) t
left join (
select distinct cust_id from t_order where ord_time>='2018-02-01' and ord_time < '2018-03-01'
) t2 on t.cust_id=t2.cust_id
这是第一个sql, 第一个子查询查出所有1月下单用户,第二个子查询查出所有2月下单用户,用第一个子查询left join 第二个子查询,这样结果集count(1) 仍然是第一个月的所有下单用户 sum(if(t2.cust_id is not null, 1, 0)) 则是二月所有下单用户且1月也下单的用户数
第二个没明白你的具体需求
select cust_id from(
select cust_id,count(cust_id) as reordered from(
select distinct cust_id from t_order where ord_time>='2018-01-01 00:00:00' and ord_time<='2018-01-31 23:59:59'
union all
select distinct cust_id from t_order where ord_time>='2018-02-01 00:00:00' ) as t1 group by cust_id
) as t2 where reordered>1