如何查找同一天进行两次交易并且连续进行不到10分钟的交易的人

时间:2020-01-18 03:27:35

标签: mysql sql

我还有另一个看起来像这样的表:

+--------+--------+------------------------+-----------------+------------+
|orderid | userid | create_time            | payment_amount  | product    |
+--------+--------+------------------------+-----------------+------------+
|20001   | 1001   | 2018-04-02 5.26.21     |       48        |  key chain |   
|20002   | 1002   | 2018-04-02 7.44.13     |       25        |  pin       |     
|20003   | 1001   | 2018-04-02 8.34.48     |      320        |  tote bag  |    
|20004   | 1001   | 2018-04-02 8.37.23     |      180        |  mug       |   
|20005   | 1003   | 2018-04-02 9.32.08     |       21        |  key chain |   
|20006   | 1002   | 2018-04-02 9.33.10     |      200        |  tumblr    |   
|....... | ...    |      ...               |      ...        |     ...    |   
+--------+--------+------------------------+-----------------+------------+

我需要编写两个查询:

  1. 查找在同一天进行两次交易,购买了哪些产品以及在第一笔交易中花费了多少的用户。

  2. 查找不到10分钟连续进行交易的用户!

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

第一查询:给出购买的产品以及在第一笔交易和第二笔交易中花费了多少

with cte as
(
  select userid, cast(create_time as date) as trx_Day 
  from tbl
  group by userid, cast(create_time as date) 
  having count(*) = 2
)
select a.userid, product, payment_amount, a.create_time            
from tbl a inner join cte b on a.userid = b.userid and 
cast(a.create_time as date) = b.trx_Day
order by a.create_time    

第二次查询:

    select distinct userid 
    from tbl a where exists(select 1 from tbl b where a.userid  = b.userid  
and ROUND((UNIX_TIMESTAMP(a.create_time) - UNIX_TIMESTAMP(b.create_time)) / 60)< 10
)
相关问题