【问题标题】:Athena/SQL query to get the desired resultAthena/SQL 查询以获得所需的结果
【发布时间】:2020-12-28 09:50:55
【问题描述】:

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

我有一个包含大量行数的表,该表如上所示。

问题

  1. 我想打印具有purchase 操作的行并且
  2. 同时,执行purchase的用户必须有view操作的行
  3. 同时,view 操作将在 purchase_date(2020-09-09) 和 purchase_date - 7days(2020-09-02) 的日期范围内。

我想在一个 sql 查询中实现这 3 点

sample_output

user  name  action      date
1    aaa    purchase  2020-09-09

如果我们看到来自样本输入的样本输出

  1. 我们的最终结果只有 purchase_events
  2. purchased_user 有一行 view 操作
  3. 并且 view2020-09-092020-09-02(购买日期,购买日期 - 7 天)的时间范围内存在

谁能为此提出一些解决方案?

【问题讨论】:

  • MySQL 还是 Athena?请仅标记一个数据库。
  • 对不起,它的雅典娜

标签: sql amazon-web-services subquery presto amazon-athena


【解决方案1】:

您可以使用窗口函数。假设“购买”是最后一个状态:

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';

【讨论】:

    【解决方案2】:

    你可以使用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
        )
    

    【讨论】:

    • 你好GMB,你能解释一下吗?
    • @siva: exists 检查过去 7 天内是否存在具有相同用户和“查看”操作的另一行。
    • 感谢专线小巴。还有一个问题,我们是否也可以使用 JOINS 实现相同的解决方案?如果是,你能告诉我怎么做吗?
    • @siva:连接在这里并不合适。如果有多个匹配的视图,它将复制原始购买行。对于你想要的,exists 是最合适的。
    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多