如何查找两个可变日期之间的重复项
How to find duplicates between two variable dates
我有以下 table:
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 中的一个查询来做到这一点?还是我必须 运行 为此编写脚本? (我知道如何单独为每一行执行此操作,但我似乎无法通过一个查询找到一种方法)。
您可以使用相关子查询来完成:
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
值之间的分钟差。
我有以下 table:
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 中的一个查询来做到这一点?还是我必须 运行 为此编写脚本? (我知道如何单独为每一行执行此操作,但我似乎无法通过一个查询找到一种方法)。
您可以使用相关子查询来完成:
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
值之间的分钟差。