携程笔试题3--2020-09-08
题目:在很多预测模型中,往往需要用到同一行为的不同周期汇总值作为特征。比如近1/7/15/30/60天购买笔数和金额。因此,怎么用简洁的sql获取这些特征是作为一个分析师必须要掌握的技能。
输入描述:
订单表edw_htl_order:
orderid bint comment (订单id)
userid bigint comment(订单id)
orderdate string comment (下单日期)
amount double comment(订单金额)
输出结果:用户id,近一天的订单数,近一天的订单金额,近七天订单数,近七天订单金额,近15天订单数,近15天订单金额
说明:为了兼容各sql引擎,我们简化约定近n天判断如下:
近1天:【‘2020-07-15’,‘2020-07-16’】
近7天:【‘2020-07-09’,‘2020-07-16’】
近15天:【‘2020-07-01’,‘2020-07-16’】
样例输入:
样例输出:
输入代码:
1 select e1.userid,e1.cnt_1d,e1.amt_1d,e2.cnt_7d,e2.amt_7d,e3.cnt_15d,e3.amt_15d 2 from (select userid, count(orderdate) cnt_1d, sum(amount) amt_1d 3 from edw_htl_order 4 where orderdate between '2020-07-15' and '2020-07-16' 5 group by userid) as e1 6 inner join 7 (select userid, count(orderdate) cnt_7d, sum(amount) amt_7d 8 from edw_htl_order 9 where orderdate between '2020-07-09' and '2020-07-16' 10 group by userid) as e2 on e1.userid = e2.userid 11 inner join 12 (select userid, count(orderdate) cnt_15d, sum(amount) amt_15d 13 from edw_htl_order 14 where orderdate between '2020-07-01' and '2020-07-16' 15 group by userid) as e3 on e2.userid = e3.userid;
输出结果: