代码之家  ›  专栏  ›  技术社区  ›  Clauric

运行累计和

  •  0
  • Clauric  · 技术社区  · 6 年前

    我有一个很大的(ish)成员数据库,我试图做一些未来的成员预测。因此,我试图获得每月输入系统的成员总数的累积值。

    我有以下代码

    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;
    

    但是,它抛出了一个错误,如下所示:

    消息130,级别15,状态1,行4 无法对包含聚合或子查询的表达式执行聚合函数。

    我想要SUM函数做的是计算从开始到那一点DB中的成员总数(包括当月的新成员)。

    2 回复  |  直到 6 年前
        1
  •  1
  •   D-Shih    6 年前

    引起的错误 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
    
        2
  •  1
  •   Gordon Linoff    6 年前

    根据你的描述,我想你想要:

    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;