我正在尝试从看起来像这样的表中拉动活动订户:
StartDate EndDate UpgradeProcessed Cancelled Recurring Created
2018-09-05 09:46:30.000 2018-10-07 09:46:30.000 1 0 1 2018-09-05 10:54:57.363
2018-09-05 09:26:32.000 2018-12-07 09:26:32.000 1 0 1 2018-09-05 10:41:09.460
2018-09-05 09:17:49.000 2018-12-07 09:17:49.000 1 0 1 2018-09-05 10:27:14.707
2018-09-05 09:21:16.000 2018-12-07 09:21:16.000 1 0 1 2018-09-05 10:27:06.593
2018-09-05 09:23:04.000 2018-10-07 09:23:04.000 1 0 1 2018-09-05 10:27:05.877
2018-09-04 09:09:42.000 2018-12-07 09:09:42.000 1 0 1 2018-09-04 10:13:59.847
2018-09-04 09:02:29.000 2018-10-07 09:02:29.000 1 0 1 2018-09-04 10:13:42.693
2018-09-04 09:27:23.000 2018-12-07 09:27:23.000 1 0 1 2018-09-04 09:27:55.110
2018-09-04 08:09:31.000 2018-12-07 08:09:31.000 1 0 1 2018-09-04 09:19:18.193
2018-09-04 08:12:20.000 2018-10-07 08:12:20.000 1 0 1 2018-09-04 09:19:18.117
2018-09-04 08:12:20.000 2018-10-07 08:12:20.000 1 0 1 2018-09-04 09:19:18.117
我想按天或周进行分组,并且每天都必须包括当天有效的所有记录,即使它们包含在先前的行中。
在上述情况下,我们将获得以下内容:
Date Count
2018-09-05 11
2018-09-04 6
我每天可以一次提取数据,如下所示:
SELECT COUNT(*) FROM [Subscriptions]
WHERE DATEADD(day, DATEDIFF(day,0, EndDate),0) >= DATEADD(day, DATEDIFF(day,0,Cast('2018-09-05' AS datetime)),0)
AND DATEADD(day, DATEDIFF(day,0, Created),0) <= DATEADD(day, DATEDIFF(day,0,Cast('2018-09-05' AS datetime)),0)
我不确定如何添加GROUP BY类型子句,该子句将包括当天活跃的每一行。
答案 0 :(得分:0)
尝试一下
SELECT CAST(StartDate AS DATE),COUNT(1)
FROM [Subscriptions]
WHERE DATEADD(day, DATEDIFF(day,0, EndDate),0) >= DATEADD(day, DATEDIFF(day,0,Cast('2018-09-05' AS datetime)),0)
AND DATEADD(day, DATEDIFF(day,0, Created),0) <= DATEADD(day, DATEDIFF(day,0,Cast('2018-09-05' AS datetime)),0)
GROUP BY CAST(StartDate AS DATE)
答案 1 :(得分:0)
好,找到答案了,我从here修改了一个脚本,制成了一个数字表,并使用该页面上的查询来启发灵感。
SELECT [stats.dates].thedate, COUNT(*)
FROM [stats.dates]
JOIN Subscriptions ON [stats.dates].thedate >= cast([StartDate] as DATE) AND [stats.dates].thedate <= cast([EndDate] as DATE)
WHERE [stats.dates].thedate >= '2017-09-04' AND [stats.dates].thedate <= '2018-09-04'
GROUP BY [stats.dates].thedate
where子句指示要获取数据的日期范围。