码迷,mamicode.com
首页 > 数据库 > 详细

sql查询连续3天有交易记录的客户

时间:2019-07-11 00:25:54      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:tin   body   sql查询   --   交易   div   group   rom   highlight   

利用表的自关联查询

表A

CUS_ID TXN_DT ID
1 20180101 1
2 20180101 2
3 20180101 3
1 20180102 4
2 20180102 5
2 20180102 6
1 20180103 7
3 20180103 8
with t as (
    select 
        cus_id
        ,txn_dt
    from a
    qualify row_number()over(partition by cus_id,txn_dt order by id ) = 1
              )
select
    cus_id   
from t m
inner join t n
on m.cus_id = n.cus_id
and m.txn_dt <= n.txn_dt +2
group by 1
having count(cus_id) = 3
;
--或者
select
    cus_id   
from a m
inner join a n
on m.cus_id = n.cus_id
and m.txn_dt <= n.txn_dt +2
group by 1
having count(distinct txn_dt) = 3
;

  

sql查询连续3天有交易记录的客户

标签:tin   body   sql查询   --   交易   div   group   rom   highlight   

原文地址:https://www.cnblogs.com/king-cobra-rko/p/11167458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!