我的数据是这样的
Installed(Days ago) Activity UserID withdraw
52 11/4/16 111 null
40 15/4/16 112 5
15 26/4/16 113 null
16 17/4/16 117 null
17 14/4/16 135 2
我需要列出在安装日期(包括)之后连续7天有活动的用户列表,但退出的用户除外。
答案 0 :(得分:0)
是的,我必须在这里做一些假设。我假设您使用的表将为用户登录的每一天存储一行。这样的事情;
CREATE TABLE #TestData (InstalledDaysAgo int, Activity datetime, UserID int, Withdraw int)
INSERT INTO #TestData
VALUES
('10','05-01-2016','111',NULL)
,('10','05-02-2016','111',NULL)
,('10','05-03-2016','111',NULL)
,('10','05-04-2016','111',NULL)
,('10','05-05-2016','111',NULL)
,('10','05-06-2016','111',NULL)
,('10','05-07-2016','111',NULL)
,('10','05-08-2016','111',NULL)
,('10','05-01-2016','112',NULL)
,('10','05-03-2016','112',NULL)
,('10','05-07-2016','112',NULL)
,('10','05-08-2016','112',NULL)
,('10','05-01-2016','113',5)
,('10','05-02-2016','113',5)
,('10','05-03-2016','113',5)
,('10','05-04-2016','113',5)
,('10','05-05-2016','113',5)
,('10','05-06-2016','113',5)
,('10','05-07-2016','113',5)
,('10','05-08-2016','113',5)
我假设您只想要一个包含所有用户的列表,安装的时间以及安装后7天内是否已登录;
SELECT DISTINCT
a.InstalledDaysAgo
,a.UserID
,CASE WHEN fw.FirstWeekLogins = 7 THEN 1 ELSE 0 END All7Days
FROM #TestData a
LEFT JOIN
(
SELECT
UserID
,SUM(CASE
WHEN Activity BETWEEN CAST((cast(GETDATE() as date)) AS datetime) -InstalledDaysAgo AND CAST((cast(GETDATE() as date)) AS datetime) -(InstalledDaysAgo-6)
THEN 1
ELSE 0
END) FirstWeekLogins
FROM #TestData
GROUP BY UserID
) fw
ON a.UserID = fw.UserID
WHERE Withdraw IS NULL
这不会解释任何InstalledDaysAgo字段小于7但应该是你的起点。
您的数据看起来像这样;
InstalledDaysAgo UserID All7Days
10 111 1
10 112 0
(别忘了这一点)
DROP TABLE #TestData