如何显示另一个子查询的日期和参考范围?

时间:2016-11-23 09:24:33

标签: sql sql-server database sql-server-2008 join

我有一系列活动表..现在我想得到每天创建的活动数量

例如。结果将是:

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的Date列,并获得该特定日期的活动计数。

AS (select count(*)     AS [Count]
from Activities act
where CAST(act.CreatedDate AS DATE) = [AllDays].[Date])

但是,这会给出错误

  

&#34;多部分标识符无法绑定&#34;

我非常感谢您对如何进行此操作并获得所需结果的帮助:

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

2 个答案:

答案 0 :(得分:0)

根据我的理解,您希望每天都有Count行。为此,您可以在给定范围之间的每一天执行Group By,然后COUNT以获得您想要的内容,如下所示

SELECT DATEADD(DAY,0, datediff(day,0, date)) As Date, COUNT(*) As Cont 
FROM #temp
WHERE date BETWEEN @startDate AND @endDate
GROUP By DATEADD(DAY,0, DATEDIFF(DAY,0, date))

答案 1 :(得分:0)

试试这个简单的例子, 创建过程并传递2参数StartDate,EndDate和Execute SP。

  declare @StartDate Date ='2016-10-01';
    declare @EndDate Date ='2016-10-10';

    select CreatedDate,COUNT(*) Count from Activities 
    where Convert(Date,CreatedDate) between @StartDate and @EndDate
    Group by CreatedDate