简体   繁体   English

SQL获取每个唯一ID的第一行以及在第一个后的x时间内具有该ID的每一行

[英]SQL Get first row of each unique ID AND each row with that ID within x time after the first

I was wondering if it is possible to have a single SQL command that returns each unique userID from a table as well as the rows containing that userID within the next 24 hours. 我想知道是否可以使用一个SQL命令在接下来的24小时内从表中返回每个唯一的用户ID以及包含该用户ID的行。

So for example I may have a table structured like: 因此,例如,我可能有一个结构如下的表:

id | userID | action | date

with a bunch of rows with thousands of unique userIDs, dozens of different actions, and dates. 一堆行,其中包含数千个唯一的用户ID,数十种不同的操作和日期。 I am basically interested in what actions each userID does within the first 24 hours, but this for all users. 我基本上对每个userID在最初的24小时内会执行什么操作感兴趣,但这对所有用户来说都是如此。

So I should get maybe 10-15 different actions for each userID, and each userID will be signing up on different days, months, or even years so it's not just grabbing all actions over a specific 24 hour period. 因此,我应该为每个用户ID采取10-15个不同的操作,并且每个用户ID将在不同的日期,月份甚至几年内进行注册,因此它不仅仅是在特定的24小时内抓取所有操作。

If I understand your question correctly, you could use a query like this: 如果我正确理解了您的问题,则可以使用以下查询:

SELECT a1.*
FROM
  actions a1 INNER JOIN (SELECT   userID, MIN(date) first_action
                         FROM     actions
                         GROUP BY userID) a2
  ON a1.userID = a2.userID AND a1.date <= first_action + INTERVAL 24 HOUR

Please see fiddle here . 请看这里的小提琴。 This query will return all actions that each user does in the first 24 hours after their first action. 此查询将返回每个用户在执行第一个操作后的前24小时内执行的所有操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM