【发布时间】:2017-04-07 05:22:04
【问题描述】:
我有一个活动表列表..现在我想获取每天创建的活动计数
例如。结果是:
Date Count
01/10/2016 100
02/10/2016 20
03/10/2016 3000
从网上搜索了几个小时,这是工作代码:
DECLARE @start_date DATE = '2016-10-01';
DECLARE @end_date DATE= '2016-10-10';
WITH AllDays
AS ( SELECT @start_date AS [Date]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
FROM AllDays
WHERE [Date] < @end_date ),
PartitionCount
AS (select count(*) AS [Count]
from Activities act
where CAST(act.CreatedDate AS DATE) = '2016-10-01')
SELECT distinct [AllDays].[Date], [PartitionCount].[Count]
FROM AllDays, PartitionCount, Activities
ORDER BY [AllDays].[Date]
OPTION (MAXRECURSION 0)
这将给出以下结果:
Date Count
01/10/2016 100
02/10/2016 100
03/10/2016 100
然而,这个只得到当天2016-10-01的计数。
所以我尝试更改这部分代码,以便活动创建日期等于 AllDays 的日期列,并获取该特定日期的活动计数。
AS (select count(*) AS [Count]
from Activities act
where CAST(act.CreatedDate AS DATE) = [AllDays].[Date])
但是,这会报错
“无法绑定多部分标识符”
非常感谢您对我如何进行此操作并获得所需结果的帮助:
Date Count
01/10/2016 100
02/10/2016 20
03/10/2016 3000
示例表如下所示
Table: Activities
ID Title CreatedDate
1 Activity1 2016-10-03 10:00:00.000
2 Activity2 2016-10-03 11:30:00.000
3 Activity3 2016-10-03 14:00:00.000
4 Activity4 2016-10-03 14:30:00.000
5 Activity5 2016-10-04 10:00:00.000
6 Activity6 2016-10-05 11:00:00.000
7 Activity7 2016-10-06 10:00:00.000
8 Activity8 2016-10-07 11:00:00.000
【问题讨论】:
-
您还需要提供要从中计算此结果的数据。
-
用表格结构添加样本数据。
-
嗨@CoderofCode,我只有一个看起来类似于此的简单表:表:活动标题 CreatedDate Activity1 2016-10-03 10:00:00.000 Activity2 2016-10-03 11:30: 00.000 Activity3 2016-10-03 14:00:00.000 Activity4 2016-10-03 14:30:00.000 Activity5 2016-10-04 10:00:00.000 Activity6 2016-10-05 11:00:00.000 Activity7 2016-10- 06 10:00:00.000 活动8 2016-10-07 11:00:00.000
-
请为给定数据添加预期结果集。并查看我的答案,如果您需要的话,请告诉我。
标签: sql sql-server database sql-server-2008 join