mysql-date差异和标志

eqzww0vc  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(277)

我是新来的 MySQL 目前正在处理一个有三列的表: trx_id, user_id, last_activity . (客户流失分析)
tbl\U活动:

表捕获用户的活动。我发现执行两项任务很困难。
1) 我想通过sql查询看到两个新列
后续交易之间的日期差异。
标记基于条件>30天。
所需表格:

2) 本研究的目标之一是确定客户何时(日期)流失。最理想的情况是在我的情况下,这将是自上次活动以来的第31天。有什么办法到达这个日期吗?
我是sql学习新手,发现很难解决上述任务的sql查询。

gzszwxb4

gzszwxb41#

试试这个:
对于sql server:

CREATE TABLE #tbl_activity(Trx_ID INT, User_Id INT, Last_Activity DATETIME)

INSERT INTO #tbl_activity VALUES(1,1100,'2015-06-08')
INSERT INTO #tbl_activity VALUES(2,1100,'2015-06-10')
INSERT INTO #tbl_activity VALUES(3,1100,'2015-06-10')
INSERT INTO #tbl_activity VALUES(4,1100,'2015-06-12')
INSERT INTO #tbl_activity VALUES(5,1100,'2015-06-13')
INSERT INTO #tbl_activity VALUES(6,1100,'2015-06-14')
INSERT INTO #tbl_activity VALUES(7,1100,'2015-09-25')

SELECT T1.Trx_ID, T1.User_Id, T1.Last_Activity
    ,DATEDIFF(DAY, T1.Last_Activity, T2.Last_Activity) days_Diff
    ,CASE WHEN DATEDIFF(DAY, T1.Last_Activity, T2.Last_Activity) >30 THEN 1 ELSE 0 END Flag
FROM #tbl_activity T1
LEFT JOIN #tbl_activity T2 ON T1.Trx_ID = T2.Trx_ID-1

DROP TABLE #tbl_activity

对于mysql:

CREATE TABLE tbl_activity(Trx_ID INT, User_Id INT, Last_Activity DATETIME)

INSERT INTO tbl_activity VALUES(1,1100,'2015-06-08')
INSERT INTO tbl_activity VALUES(2,1100,'2015-06-10')
INSERT INTO tbl_activity VALUES(3,1100,'2015-06-10')
INSERT INTO tbl_activity VALUES(4,1100,'2015-06-12')
INSERT INTO tbl_activity VALUES(5,1100,'2015-06-13')
INSERT INTO tbl_activity VALUES(6,1100,'2015-06-14')
INSERT INTO tbl_activity VALUES(7,1100,'2015-09-25')

SELECT T1.Trx_ID, T1.User_Id, T1.Last_Activity
    ,DATEDIFF(T2.Last_Activity, T1.Last_Activity) days_Diff
    ,CASE WHEN DATEDIFF(T2.Last_Activity, T1.Last_Activity) >30 THEN 1 ELSE 0 END Flag
FROM tbl_activity T1
LEFT JOIN tbl_activity T2 ON T1.Trx_ID = T2.Trx_ID-1

DROP TABLE tbl_activity

试试这个
输出:

Trx_ID  User_Id Last_Activity           days_Diff   Flag
1       1100    2015-06-08 00:00:00.000     2       0
2       1100    2015-06-10 00:00:00.000     0       0
3       1100    2015-06-10 00:00:00.000     2       0
4       1100    2015-06-12 00:00:00.000     1       0
5       1100    2015-06-13 00:00:00.000     1       0
6       1100    2015-06-14 00:00:00.000     103     1
7       1100    2015-09-25 00:00:00.000     NULL    0

相关问题