查找在历史数据中30天内重新访问的用户的记录

时间:2015-12-15 16:19:42

标签: mysql

我尝试创建一个MySQL查询,该查询将返回人员VisitorID在30天DateOfService内返回时的所有行。理想情况下,我希望查询返回所有字段,但示例具有相关字段以使查询起作用。

表格样本

VisitorID DateOfService Cost   TransactionID
001       2008-08-15    150.00 11-235-24 
001       2008-09-07    175.00 11-272-50
002       2008-08-15    155.00 11-688-14 
002       2008-09-16    181.00 11-841-67
001       2011-01-07    190.00 12-851-41
001       2011-01-18    100.00 12-901-55
003       2011-02-05    150.00 12-951-14
003       2011-02-15    180.00 12-998-51

理想的查询结果

VisitorID DateOfService Cost   TransactionID
001       2008-09-07    175.00 11-272-50
001       2011-01-18    100.00 12-901-55
003       2011-02-15    180.00 12-998-51

我尝试过使用group by的变体,但我似乎无法在滚动的30天窗口中完成它。

2 个答案:

答案 0 :(得分:2)

SELECT t1.*
FROM table t1 
INNER JOIN table t2 
  ON t1.VisitorID = t2.VisitorID AND
     t1.TransactionID != t2.TransactionID AND
     t1.DateOfService > t2.DateOfService AND 
     datediff(t1.DateOfService, t2.DateOfService) < 30

demo on sqlfiddle

答案 1 :(得分:0)

您可以使用相关子查询来获取当前/以前记录之间的天数差异:

SELECT `VisitorID`, `DateOfService`, `Cost`, `TransactionID`
FROM (
  SELECT `VisitorID`, `DateOfService`, `Cost`, `TransactionID`,
         DATEDIFF (`DateOfService`,       
         (SELECT `DateOfService`
          FROM mytable AS t2
          WHERE t1.`VisitorID` = t2.`VisitorID` AND 
                t1.`DateOfService` > t2.`DateOfService`
          ORDER BY t2.`DateOfService` DESC 
          LIMIT 1)) AS daysDiff
  FROM mytable AS t1) AS t
WHERE daysDiff <= 30

外部查询只会过滤掉差异大于30天的行。

Demo here