如何加入具有容差的时间戳列
How to join on timestamp columns with tolerance
如何允许 1 - 10 秒的容差?
我有 2 个 table 有时间戳,但相差 1-10 秒。我正在使用内部连接来比较它们。我在两个 table 中都有 phone 个数字(列)匹配但不能使它们与时间戳匹配(仅限时间)。为了允许一定的容差,我可以使用像 cast(DateCreated as Time) = cast(TIMESTAMP as time) + 5
这样的表达式。但我不想每一秒都这样做。
SELECT Time_To_Sec(cast("table1_DateCreated" as time)) as DateCreated
, Time_To_Sec(cast("table2"."Timestamp" as time)) as Timestampe
, "Direction","FromTW", "ToTW", "table2"."ANI","table2"."CALL ID"
, "table2"."Disposition"
FROM "calls and time"
INNER JOIN "table2" on cast(DateCreated as Time)=cast(TIMESTAMP as time)+5
and FromTW="table2"."ANI"
如果可能,我希望看到以下结果:
table1(DateCreated) | table2(Timestamp) | compared results
---------------------+---------------------+-----------------
5000 | 5005 | table3
5001 | 5009 | table3
5001 | 5050 | not in table3
如果满足条件则发送至table3,不满足条件则不发送至table3.
使用 Zoho 报告,因此我不确定他们使用的是什么类型的数据库。 Postgres、MySQL 等
检查两个时间戳的绝对差,伪代码:
if (abs($timestamp1 - $timestamp2) <= $tolerance) { ... }
如果两个表中的时间戳都可以是off by 1-10 seconds
,那么逻辑上匹配的最大容差是20秒(每边+/- 10)。
在 Postgres 中测试:
SELECT *
FROM "calls and time" t1
JOIN table2 t2 ON t2."TIMESTAMP" BETWEEN t1."DateCreated" - interval '20 sec'
AND t1."DateCreated" + interval '20 sec';
WHERE t1."FromTW" = t2."ANI" -- FromTW or "FromTW" ?
这是一个 sargable 表达式,允许在 x
:
上使用索引
x BETWEEN y - interval '20 sec'
AND y + interval '20 sec'
"calls and time"
、"TIMESTAMP"
、"FromTW"
是 非常不幸的标识符 ,顺便说一句。坚持使用合法的、不带引号的名称可以省去一些麻烦。
如何允许 1 - 10 秒的容差?
我有 2 个 table 有时间戳,但相差 1-10 秒。我正在使用内部连接来比较它们。我在两个 table 中都有 phone 个数字(列)匹配但不能使它们与时间戳匹配(仅限时间)。为了允许一定的容差,我可以使用像 cast(DateCreated as Time) = cast(TIMESTAMP as time) + 5
这样的表达式。但我不想每一秒都这样做。
SELECT Time_To_Sec(cast("table1_DateCreated" as time)) as DateCreated
, Time_To_Sec(cast("table2"."Timestamp" as time)) as Timestampe
, "Direction","FromTW", "ToTW", "table2"."ANI","table2"."CALL ID"
, "table2"."Disposition"
FROM "calls and time"
INNER JOIN "table2" on cast(DateCreated as Time)=cast(TIMESTAMP as time)+5
and FromTW="table2"."ANI"
如果可能,我希望看到以下结果:
table1(DateCreated) | table2(Timestamp) | compared results
---------------------+---------------------+-----------------
5000 | 5005 | table3
5001 | 5009 | table3
5001 | 5050 | not in table3
如果满足条件则发送至table3,不满足条件则不发送至table3.
使用 Zoho 报告,因此我不确定他们使用的是什么类型的数据库。 Postgres、MySQL 等
检查两个时间戳的绝对差,伪代码:
if (abs($timestamp1 - $timestamp2) <= $tolerance) { ... }
如果两个表中的时间戳都可以是off by 1-10 seconds
,那么逻辑上匹配的最大容差是20秒(每边+/- 10)。
在 Postgres 中测试:
SELECT *
FROM "calls and time" t1
JOIN table2 t2 ON t2."TIMESTAMP" BETWEEN t1."DateCreated" - interval '20 sec'
AND t1."DateCreated" + interval '20 sec';
WHERE t1."FromTW" = t2."ANI" -- FromTW or "FromTW" ?
这是一个 sargable 表达式,允许在 x
:
x BETWEEN y - interval '20 sec'
AND y + interval '20 sec'
"calls and time"
、"TIMESTAMP"
、"FromTW"
是 非常不幸的标识符 ,顺便说一句。坚持使用合法的、不带引号的名称可以省去一些麻烦。