我是MySQL
的新手,目前正在开发一个包含三列的表:trx_id, user_id, last_activity
。 (流失分析)
tbl_activity:
用户的表捕获活动。我发现执行两项任务很困难。
1)我想通过SQL查询看到两个新列
所需表:
2)本研究的目标之一是确定客户流失的时间(日期)。理想情况下,在我的情况下,它将是自上次活动以来的第31天。到达这个日期的任何方式?
我是SQL学习的新手,发现很难解决上述任务的SQL查询。
答案 0 :(得分:1)
试试这个:
对于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