【问题标题】:SQL to find the most recent active eventSQL 查找最近的活动事件
【发布时间】:2021-06-21 18:33:35
【问题描述】:

我有 2 个表、请求和事件。见下文。

requests columns: request_id(primary_key), user_id, request_timestamp.

events columns: event_id(primary_key), user_id, event_start_time, event_end_time

需要注意的是,给定一个用户 ID,所有事件持续时间都是互斥的。

现在我想编写一个 SQL 来连接这两个表并生成如下数据:

request_id, user_id, event_id, event_start_time, event_end_time, request_timestamp

加入时有两种情况/限制:

  1. 如果在事件处于活动状态时发出请求,我们应该接收它,即request_timestamp >= events.start_time AND request_timestamp <= events.end_time。然后完成

  2. 如果没有活动事件,我们需要在请求之前提取结束的事件,即找到与用户关联的所有事件并过滤掉 start_time 大于请求时间的事件。然后选择带有MAX(end_time)的事件。

我在这方面花了很多时间,但没能把它做好。我认为我要解决的问题并不是唯一的。

感谢任何帮助。

【问题讨论】:

  • 我删除了不一致的数据库标签。请仅使用您真正使用的数据库进行标记。如果有两个活动事件怎么办?
  • Edit 问题并展示您已经尝试过的内容。解释失败的原因/位置。具体(错误消息、意外结果等)。
  • @GordonLinoff 我正在使用 Presto,我刚刚更新了标签。对我来说重要的部分是我学会了利用 SQL 中的分支语句来执行此类查询。我使用的数据库类型并不重要。我的用例确保事件周期是互斥的。所以不可能有 2 个活动事件。

标签: sql presto


【解决方案1】:

如果您希望每个请求一个事件,您可以使用相关子查询:

select r.*,
       (select e.event_id
        from events e
        where e.user_id = r.user_id and
              e.event_start_time <= request_timestamp
        order by (case when request_timestamp between event_start_time and event_end_time then 1 else 2 end),
                 request_timestamp desc
        limit 1
       ) as event_id
from requests r;

然后您可以join 返回事件表以获取其余信息:

select r.*, e.*
from (select r.*,
             (select e.event_id
              from events e
              where e.user_id = r.user_id and
                    e.event_start_time <= request_timestamp
              order by (case when request_timestamp between event_start_time and event_end_time then 1 else 2 end),
                       request_timestamp desc
              limit 1
             ) as event_id
      from requests r
     ) r left join
     events e
     on e.event_id = r.event_id;

【讨论】:

  • 感谢您的快速回复。我认为这是一个很好的解决方案。我之前几乎没有在 SQL 中使用过任何分支语句。我认为你使用case when 的方式在这里真的很聪明。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 2019-02-13
  • 1970-01-01
相关资源
最近更新 更多