sql server计算不同年份的每月累计数量

时间:2014-03-31 18:02:22

标签: sql sql-server

我有一张表" date"柱。每行代表一项调查。

  date
    11/19/2013 5:51:41 PM
    11/22/2013 1:30:38 PM
    11/23/2013 3:09:17 PM
    12/2/2014 5:24:17 PM
    12/25/2014 11:42:56 AM
    1/6/2014 2:24:49 PM

我想累计计算每个月的调查数量。如上表所示,2013年11月 3次调查,2013年12月 2次调查 2014年1月调查。每月的累计调查数量为:

month | year | number_of_survey
11    | 2013 | 3
12    | 2013 | 5
1     | 2014 | 6

我有这个查询显示2013年的正确调查数量,2014年的调查数量不是累积的。

with SurveyPerMonth as -- no of Survey per month
       ( 
         select datepart(month, s.date) as month, 
            datepart(year, s.date) as year, 
            count(*) as no_of_surveys
         from myTable s

         group by datepart(year, s.date), datepart(month, s.date)
       )

  select p1.month, p1.year, sum(p2.no_of_surveys) as surveys -- cumulatively
  from SurveyPerMonth p1
  inner join SurveyPerMonth p2 on p1.month >= p2.month and p1.year>=p2.year **-- the problem is probably comes from this line of code**

  group by p1.month, p1.year
  order by p1.year, p1.month;

此查询返回:

month | year | surveys
11    | 2013 | 3
12    | 2013 | 5
1     | 2014 | 1     // 2014 is not cumulative

我如何计算2014年每月的累计调查数量?

2 个答案:

答案 0 :(得分:2)

这样的东西?

SELECT date = create_date INTO #myTable FROM master.sys.objects

;WITH perMonth ( [year], [month], [no_of_surveys])
   AS (SELECT DatePart(year, s.date) , 
              DatePart(month, s.date), 
              COUNT(*)
         FROM #myTable s
        GROUP BY datepart(year, s.date), 
                 datepart(month, s.date))
SELECT [year],
       [month],
       [no_of_surveys] = ( SELECT SUM([no_of_surveys])
                             FROM perMonth agg
                            WHERE (agg.[year] < pm.[year])
                               OR (agg.[year] = pm.[year] AND agg.[month] <= pm.[month]))
  FROM perMonth pm
 ORDER BY [year], [month]

编辑:似乎我错过了<>的球,修复了它并添加了小例子

答案 1 :(得分:0)

' - 这应该有用。我添加了一个新专栏'monthyear'

   with surveypermonth as -- no of survey per month
     ( 
        select datepart(month, s.date) as month, 
        datepart(year, s.date) as year, 
        datepart(year, s.date) *100 + datepart(month, s.date) as monthyear,
        count(*) as no_of_surveys
        from test s
        group by datepart(year, s.date), datepart(month, s.date),datepart(year, s.date)*100 + datepart(month, s.date) 
    )

        select a.month,substring(cast(monthyear as varchar(6)),1,4) as year,surveys from 
        (
        select p1.month, p1.monthyear as monthyear, sum(p2.no_of_surveys) as surveys 
        from surveypermonth p1
        inner join surveypermonth p2 on p1.monthyear>=p2.monthyear 
        group by p1.month, p1.monthyear
        --order by p1.monthyear, p1.month
        )a