我正在尝试编写一个 Athena 查询,该查询将创建可在营销电子邮件发出后用于分析的前后数据。
代码运行后,我得到以下结果,因为我不知道如何告诉 Athena 如果某个成员在特定时间段内没有交易,则无论如何将该行添加到他们的年龄中,然后将其置零对于“net_amount”和“total_transactions”:
客户ID | 年龄 | 净额 | total_transactions | 期间 |
---|---|---|---|---|
ABCDRF | 25 | 85.0 | 2 | 邮寄 |
HDWSAZ | 37 | 23.98 | 1 | 前 |
HDWSAZ | 37 | 56.34 | 2 | 邮寄 |
OAYDI | 42 | 8.2 | 1 | 前 |
OAYDI | 42 | 98.29 | 4 | 邮寄 |
美国贸易协会 | 31 | 88.62 | 1 | 前 |
马里斯 | 56 | 34.16 | 2 | 前 |
如您所见,上表没有“ABCDRF”的前期行,也没有“IUSTRA”和“MAHRYS”的后期行,但我想将其添加为“net_amount”的零" 和 "total_transactions" 以及为缺失的期间(之前或之后)插入正确值的年龄。
我使用的代码是:
select distinct(customer_ID) as customer_ID, age, sum(net_amount) as net_amount, sum(lineitem) as total_visits, (case
when trans_date >= (current_timestamp - interval '18' month) AND trans_date < (current_timestamp - interval '6' month) then 'Post'
when trans_date >= (current_timestamp - interval '30' month) AND trans_date < (current_timestamp - interval '18' month) then 'Pre'
else 'nope'
end) as Period
from trans_history
where trans_date >= (current_timestamp - interval '30' month) AND trans_date < (current_timestamp - interval '6' month)
group by 1, 5
order by 1 desc;
我想要的:
客户ID | 年龄 | 净额 | total_transactions | 期间 |
---|---|---|---|---|
ABCDRF | 25 | 0 | 0 | 前 |
ABCDRF | 25 | 85.0 | 2 | 邮寄 |
HDWSAZ | 37 | 23.98 | 1 | 前 |
HDWSAZ | 37 | 56.34 | 2 | 邮寄 |
OAYDI | 42 | 8.2 | 1 | 前 |
OAYDI | 42 | 98.29 | 4 | 邮寄 |
美国贸易协会 | 31 | 88.62 | 1 | 前 |
IUSTRA | 31 | 0 | 0 | 发布 |
马里斯 | 56 | 34.16 | 2 | 前 |
马里斯 | 56 | 0 | 0 | 发布 |
知道如何在 Athena 中使用此代码添加这些行吗?我觉得这只是我需要在“case when”语句中添加的内容,但我无法弄清楚。
谢谢! 马克
case
表达式在这里是不够的,因为一些客户确实 not 有两个时期的数据。
相反,一种方法是
cross join
具有固定、预定义期间的客户列表,以生成所有可能的组合。 那么,我们可以带一个left join
的表,然后聚合:
select c.customer_id, c.age, p.period
coalesce(sum(net_amount), 0) as net_amount,
coalesce(sum(lineitem) , 0) as total_visits
from (select distinct customer_id, age from trans_history) c
cross join (
select 'Post' as period
current_timestamp - interval '18' month as start_date,
current_timestamp - interval '6' month as end_date
union all
select 'Pre',
current_timestamp - interval '30' month,
current_timestamp - interval '18' month
) p
left join trans_history t
on t.customer_id = c.customer_id
and t.trans_date >= p.start_date
and t.trans_date < p.end_date
group by c.customer_id, c.age, p.period