我有下表:
id | whenCreated | callingNumber |
---|--------------------------------|
1 | 1-1-2016 9:00 | 0612345678 |
2 | 1-1-2016 9:10 | 0623456789 |
3 | 1-1-2016 9:55 | 0612345678 |
4 | 1-1-2016 10:15 | 0623456789 |
5 | 1-1-2016 11:00 | 0623456789 |
etc.
Datatypes:
id = int (AI)
whenCreated = datetime
callingNumber = varchar
我想分析一下有多少人在他们之前的通话后的一段时间内回电(例如,假设1小时)。为此,我想找一个人在之前一段时间之前打过电话的次数。在这个例子中,结果应该是这样的:
id | whenCreated | callingNumber | prevCalls |
---|--------------------------------|-----------|
1 | 1-1-2016 9:00 | 0612345678 | 0 | < 0, because no previous calls
2 | 1-1-2016 9:10 | 0623456789 | 0 | < 0, because no previous calls
3 | 1-1-2016 9:55 | 0612345678 | 1 | < 1, because one call from this number in the last hour
4 | 1-1-2016 10:15 | 0623456789 | 0 | < 0, there was one earlier call from this number, but it was more than an hour ago
5 | 1-1-2016 11:00 | 0623456789 | 1 | < 1, because one call from this number in the last hour
etc.
有什么方法可以用MySQL中的一个查询来做到这一点吗?或者我必须为此运行脚本? (我知道如何单独为每一行做这件事,我似乎无法通过一个查询找到一种方法)。
答案 0 :(得分:1)
您可以使用相关子查询来执行此操作:
SELECT id, whenCreated, callingNumber,
(SELECT COUNT(*)
FROM mytable AS t2
WHERE t2.callingNumber = t1.callingNumber AND
t2.id < t1.id AND
TIMESTAMPDIFF(MINUTE, t2.whenCreated, t1.whenCreated) < 60)
FROM mytable AS t1
该查询使用TIMESTAMPDIFF
来计算两个whenCreated
值之间的差异。