我有一个登录表,其中包含客户的 ID 和登录时间的时间戳(customerid
,timestamp
)。
我希望获得在 60 分钟内至少登录 3 次的所有客户 ID。顺便说一句,登录表很大。自行加入不是一种选择。
例如:
customer id | timestamp
1 | 2016-08-16 00:00
2 | 2016-08-16 00:00
3 | 2016-08-16 00:00
1 | 2016-08-16 00:25
2 | 2016-08-16 01:25
3 | 2016-08-16 00:25
1 | 2016-08-16 00:47
2 | 2016-08-16 01:27
3 | 2016-08-16 02:25
3 | 2016-08-16 03:25
1 | 2016-08-16 01:05
对于这个例子,查询应该只返回 customerid
1。有什么想法吗?
最佳答案
使用 rexTester 测试:http://rextester.com/RMST24716 (感谢 TT. !)
CREATE TABLE loginTable (id INT NOT NULL, timestamp DATETIME NOT NULL);
INSERT INTO loginTable (id, timestamp) values
( 1, '2016-08-16 00:00'),
( 2, '2016-08-16 00:00'),
( 3, '2016-08-16 00:00'),
( 1, '2016-08-16 00:25'),
( 2, '2016-08-16 01:25'),
( 3, '2016-08-16 00:25'),
( 1, '2016-08-16 00:47'),
( 2, '2016-08-16 01:27'),
( 3, '2016-08-16 02:25'),
( 3, '2016-08-16 03:25'),
( 1, '2016-08-16 01:05');
SELECT distinct a.id
FROM loginTable as a
join loginTable as b on a.id = b.id and a.timestamp < b.timestamp
join loginTable as c on b.id = c.id and b.timestamp < c.timestamp
where Datediff(minute, a.timestamp, c.timestamp) <= 60;
关于sql-server - 选择在一个时间间隔内至少登录 3 次的所有客户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224842/