运行累积总和

时间:2018-08-03 14:00:32

标签: sql sql-server

我有一个很大的(会员)会员数据库,我在这里尝试做一些将来的会员计划。因此,我试图获取每月每月输入到系统的成员总数。

我有以下代码

select  YEAR(datejoined) as YDJ,
    MONTH(datejoined) as MDJ,
    COUNT(MONTH(datejoined)) as CDJ,
    SUM(Count(Month(DateJoined))) as SCDJ
From Member
Group by YEAR(datejoined), MONTH(datejoined)
Order by YEAR(DateJoined) asc, MONTH(datejoined) asc;

但是它会引发如下错误:

  

第15层状态1的第4行消息130   无法对包含聚合或子查询的表达式执行聚合功能。

我希望SUM函数要做的是计算从开始到该点(包括该月的新成员)中DB中的成员总数。

2 个答案:

答案 0 :(得分:1)

根据您的描述,我认为您想要

select YEAR(datejoined) as YDJ, MONTH(datejoined) as MDJ,
       COUNT(*) as CDJ,
       SUM(COUNT(*)) OVER (ORDER BY YEAR(datejoined), MONTH(datejoined)) as running_CDJ
    SUM(Count(Month(DateJoined))) as SCDJ
From Member
Group by YEAR(datejoined), MONTH(datejoined)
Order by YEAR(DateJoined) asc, MONTH(datejoined) asc;

SQL Server 2012+中提供了累计金额。在早期版本中,您可以使用APPLY

with t as (
      select YEAR(datejoined) as YDJ, MONTH(datejoined) as MDJ,
             COUNT(*) as CDJ,
             SUM(COUNT(*)) OVER (ORDER BY YEAR(datejoined), MONTH(datejoined)) as running_CDJ
      From Member
      Group by YEAR(datejoined), MONTH(datejoined)
     )
select t.*, t2.running_cdj
from t outer apply
     (select sum(CDJ) as running_CDJ
      from t t2
      where t2.ydj < t.ydj or
            t2.ydj = t.ydj and t2.mdj <= t2.mdj
     ) t2;

答案 1 :(得分:1)

SUM(Count(Month(DateJoined))) as SCDJ

引起的错误

聚合函数一次不能包含聚合函数

您需要编写子查询来解决

如果要累积总和,则可以将窗口功能SUM

一起使用
SELECT t.*,SUM(CDJ) OVER (ORDER BY YDJ ,MDJ) as SCDJ
FROM (
    select  
        YEAR(datejoined) as YDJ,
        MONTH(datejoined) as MDJ,
        COUNT(datejoined) as CDJ
    From Member
    Group by YEAR(datejoined), MONTH(datejoined)
) t 
Order by YDJ asc, 
         MDJ asc