-1

下面是表1中的数据

BUYER_ID   |   ITEM_ID         |    CREATED_TIME
-----------+-------------------+------------------------
1345653        110909316904         2012-07-09 21:29:06
1345653        151851771618         2012-07-09 19:57:33
1345653        221065796761         2012-07-09 19:31:48
1345653        400307563710         2012-07-09 18:57:33
1345653        310411560125         2012-07-09 16:09:49
1345653        120945302103         2012-07-09 13:40:23
1345653        261060982989         2012-07-09 09:02:21

下面是表2中的数据

USER_ID   |   PRODUCT_ID           |    LAST_TIME
-----------+-------------------+----------------------
1345653       110909316904         2012-07-09 21:30:06
1345653       151851771618         2012-07-09 19:57:33
1345653       221065796761         2012-07-09 19:31:48
1345653       400307563710         2012-07-09 18:57:33

问题陈述:-

我需要Table2比较Table1onBUYER_IDUSER_IDCREATED_TIME如果和之间的差异LAST_TIME大于,我需要找到不匹配的计数15 minutes

因此,如果您查看上面的示例,则可以看到两个表中的第一行ITEM_IDandPRODUCT_ID相同但又不相同,CREATED_TIME并且LAST_TIME这两次之间的差异仅为 1 分钟。因此,如果差异大于 15 分钟,那么我想将它们显示为错误。所以预期的输出将是上述情况-

BUYER_ID    ERROR
1345653       1
4

1 回答 1

1

首先,找到所有匹配的买家:

select *
from table1 t1 join
     table2 t2
     on t1.buyer_id = t2.user_id and
        datediff(min, t1.created_time, t2.last_time) between -15 and 15

使用它,现在找到不匹配的情况:

with matches as (
     select *
     from table1 t1 join
          table2 t2
          on t1.buyer_id = t2.user_id and
             datediff(min, t1.created_time, t2.last_time) between -15 and 15
    )
select *
from table1 t1 left outer join
     matches m
     on t1.buyer_id = m.user_id and
        t1.product_id = m.product_id and
        t1.created_time = m.created_time
where m.buyer_id is null
于 2012-07-23T22:21:05.520 回答