累积总和不同

时间:2017-05-15 11:11:13

标签: sql sql-server running-total

我的视图refv_ActiveOpenSuburbName, Weeks, ServiceCount,我想创建第二个视图,显示每周累积ServiceCount。视图必须具有不同的周和郊区名称。例如:

  SuburbName |Weeks|ServiceCount|Accumulative
   Pretoria  |1    |100         |100
   Pretoria  |2    |30          |130
 Johannesburg|1    |30          |30
 Johannesburg|2    |20          |50

以上是我想要显示的结果。对于每个郊区,应该有一个列显示不同的郊区以及每个郊区每周的运行总量。我设法获得了总体运行总数,但这不是我想要的。请协助

3 个答案:

答案 0 :(得分:2)

ANSI-SQL,应该适用于任何RDBMS:

SELECT t1.SuburbName, t1.Weeks, t1.ServiceCount, sum(t2.ServiceCount) as Accumulative
FROM refv_ActiveOpen t1
INNER JOIN refv_ActiveOpen t2
  ON t1.SuburbName = t2.SuburbName -- Same suburb
  AND t1.Weeks >= t2.Weeks -- All the weeks up to the week from t1.
GROUP BY t1.SuburbName, t1.Weeks, t1.ServiceCount

这使用自联接为表的每一行(别名t1)生成同一郊区的匹配行集,其中周数相同或更低。然后对后面的行进行求和以获得前几周的累计服务编号。

答案 1 :(得分:0)

在大多数数据库中,您可以使用ANSI标准累积和函数:

select t.*,
       sum(Service_Count) over (partition by SuburbName order by weeks) as accumulative
from refv_ActiveOpen t;

自2012版以来,SQL Server一直支持此功能。

答案 2 :(得分:0)

您可以通过窗口函数使用总和和顺序

Select *, accumulative =  sum(service count) over(partition by suburb name, weeks order by weeks) from yourtable