如何编写SQL查询筛选指定复访客户并排除已召回对象
客户到访数据查询需求与解决方案
客户到访数据表
| CustomerID | CustTrans |
|---|---|
| C001 | 2022-09-03 |
| C002 | 2022-09-02 |
| C003 | 2022-09-03 |
| C004 | 2022-09-02 |
| C002 | 2022-09-08 |
| C001 | 2022-09-05 |
| C002 | 2022-09-11 |
| C002 | 2022-09-23 |
| C004 | 2022-09-19 |
| C001 | 2022-09-18 |
| C003 | 2022-09-26 |
| C005 | 2022-09-17 |
| C006 | 2022-09-25 |
| C001 | 2022-09-25 |
| C005 | 2022-09-10 |
此前的查询实现
我曾用以下SQL查询获取2022-08-29至2022-09-04到访且2022-09-05至2022-09-11复访的客户ID:
select distinct CustomerID from trydata where CustTrans between '2022-09-01' and '2022-09-04' and CustomerID in (select distinct CustomerID from trydata where CustTrans between '2022-09-05' and '2022-09-11')
查询结果为:C001 C002
当前查询需求与实现
需要编写SQL查询满足以下条件的客户ID:
- 在2022-08-29至2022-09-04期间有到访记录;
- 在2022-09-12至2022-09-18期间有复访记录;
- 排除在2022-09-05至2022-09-11期间已有到访记录的客户。
对应的SQL语句如下:
select distinct CustomerID from trydata where CustTrans between '2022-08-29' and '2022-09-04' and CustomerID in (select distinct CustomerID from trydata where CustTrans between '2022-09-12' and '2022-09-18') and CustomerID not in (select distinct CustomerID from trydata where CustTrans between '2022-09-05' and '2022-09-11')
查询结果说明
根据给定数据表,该查询结果为空。原因如下:
- C001满足前两个条件,但在2022-09-05至2022-09-11期间有到访记录,被排除;
- C005在2022-09-12至2022-09-18期间有到访记录,但不符合第一个时间段的到访条件;
- 其他客户要么不满足前两个条件,要么被第三个排除条件过滤。
内容的提问来源于stack exchange,提问作者Tasya Fauzia Fitriasari
相关产品推荐
相关产品推荐

