分组计数的运行总计

时间:2018-08-14 04:47:25

标签: sql-server-2012

希望有人可以提供帮助。。。我有一个精神上的空白。。我确信这很容易。。。

我需要在“视图”中添加“运行总额”列。

我的表格有两个我要利用的主要字段

AccNo和开始日期。我想计算按年和月分组的Accno。

到目前为止,我正在使用

select      {fn Monthname(startdate) } as MonthName,
            YEAR(startdate) as Year,
            count(accno) as [Count]
from        DR_ACCS
where       startdate > '01/01/2016'
group by    { fn MONTHNAME(STARTDATE) }, Month(STARTDATE), year(startdate)
order by    year(startdate),month(startdate)

这给了我

MonthName Year  Count
January   2016  24
February  2016  33
March     2016  47
April     2016  25
May       2016  34
June      2016  29
July      2016  46
August    2016  51

但是我现在要添加“运行总额”列。

1 个答案:

答案 0 :(得分:0)

请尝试这个。

;With CTE as (
select      {fn Monthname(startdate) } as MonthName,
            YEAR(startdate) as Year,
            count(accno) as [Count]
from        DR_ACCS
where       startdate > '01/01/2016'
group by    { fn MONTHNAME(STARTDATE) }, Month(STARTDATE), year(startdate)
order by    year(startdate),month(startdate)
)
select monthname,year,count,sum(count) over(order by count)Running total from cte
group by monthname,year,count,