Athena/SQL 查询得到想要的结果
Athena/SQL query to get the desired result
sample_input_table
user name action date
1 aaa view 2020-09-03
2 bbb view 2020-09-02
3 ccc view 2020-08-28
4 ddd view 2020-08-25
1 aaa purchase 2020-09-09
我有一个包含大量行的 table,table 看起来像上面那样。
问题
- 我想打印具有
purchase
操作和 的行
- 同时,执行
purchase
的用户必须具有 view
操作的行
- 同时,
view
操作将在 purchase_date(2020-09-09
) 和 purchase_date - 7 天 (2020-09-02
).
我想一次实现这3点sql查询
sample_output
user name action date
1 aaa purchase 2020-09-09
如果我们看到样本输入的样本输出
- 我们的最终结果只有purchase_events
- purchased_user 与
view
动作发生冲突
- 并且
view
在 2020-09-09
和 2020-09-02
的时间范围内(purchased_date,purchased_date - 7 天)
有人可以为此提出一些解决方案吗?
您可以使用 exists
:
select t.*
from mytable t
where t.action = 'purchase' and exists (
select 1
from mytable t1
where
t1.user = t.user
and t1.action = 'view'
and t1.date >= t.date - interval '7' day
and t1.date < t.date
)
您可以使用 window 功能。假设“购买”是最后一个状态:
select t.*
from (select t.*,
max(case when action = 'purchase' then date end) over (partition by user) as purchase_date,
max(case when action = 'view' then date end) over (partition by user) as max_view_date
from t
) t
where action = 'purchase' and
max_view_date >= purchase_date - interval '7 day';
sample_input_table
user name action date
1 aaa view 2020-09-03
2 bbb view 2020-09-02
3 ccc view 2020-08-28
4 ddd view 2020-08-25
1 aaa purchase 2020-09-09
我有一个包含大量行的 table,table 看起来像上面那样。
问题
- 我想打印具有
purchase
操作和 的行
- 同时,执行
purchase
的用户必须具有view
操作的行 - 同时,
view
操作将在 purchase_date(2020-09-09
) 和 purchase_date - 7 天 (2020-09-02
).
我想一次实现这3点sql查询
sample_output
user name action date
1 aaa purchase 2020-09-09
如果我们看到样本输入的样本输出
- 我们的最终结果只有purchase_events
- purchased_user 与
view
动作发生冲突 - 并且
view
在2020-09-09
和2020-09-02
的时间范围内(purchased_date,purchased_date - 7 天)
有人可以为此提出一些解决方案吗?
您可以使用 exists
:
select t.*
from mytable t
where t.action = 'purchase' and exists (
select 1
from mytable t1
where
t1.user = t.user
and t1.action = 'view'
and t1.date >= t.date - interval '7' day
and t1.date < t.date
)
您可以使用 window 功能。假设“购买”是最后一个状态:
select t.*
from (select t.*,
max(case when action = 'purchase' then date end) over (partition by user) as purchase_date,
max(case when action = 'view' then date end) over (partition by user) as max_view_date
from t
) t
where action = 'purchase' and
max_view_date >= purchase_date - interval '7 day';