在2008年不使用Rows Unbounded Preceding计算运行总计

时间:2017-09-08 08:42:00

标签: sql sql-server-2008 running-total

我有以下查询可以计算SQL Server 2016中的运行总计

Select
    BranchNo
    ,FiscalWeek
    ,SalesExVAT
    ,Sum(SalesExVAT) Over (Partition By BranchNo Order By FiscalWeek Rows Unbounded Preceding) As cumulative_sales
From 
    [EUUKSQL01].[DASHBOARD].[dbo].[SalesAggregateWeek]

Where 
    BranchNO in (1,4,7)
    And FiscalYear = 2017

但是,我现在的任务是在只使用Server 2008的旧服务器上使用它,然后该功能不可用。

我尝试过自我联接来重新创建它,但它只适用于单个分支,因为我似乎无法像上面那样对数据进行分区。

我可以使用替代品吗?

这是我尝试使用自我加入的方式:

Select  
    sa.BranchNo
    ,sa.FiscalWeek
    ,sa.SalesExVAT
    ,Sum(sb.SalesExVAT) As cumulative_sales

From
    [EUUKSQL01].[DASHBOARD].[dbo].[SalesAggregateWeek] sa

Inner Join
    [EUUKSQL01].[DASHBOARD].[dbo].[SalesAggregateWeek] sb
    On sa.FiscalWeek >= sb.FiscalWeek

Where
    sa.FiscalYear = 2017
    And sa.BranchNo = 1
    And sb.FiscalYear = 2017
    And sb.BranchNo = 1

Group By
    sa.BranchNo
    ,sa.FiscalWeek
    ,sa.SalesExVAT

Order By
    sa.BranchNo
    ,sa.FiscalWeek
    ,sa.SalesExVAT

1 个答案:

答案 0 :(得分:1)

为此,我倾向于使用outer apply或相关子查询。与原始查询等效的内容应为:

select daw.BranchNo, daw.FiscalWeek, daw.SalesExVAT,
       (select Sum(daw2.SalesExVAT)
        from [EUUKSQL01].[DASHBOARD].[dbo].[SalesAggregateWeek] daw2
        where daw2.BranchNo = daw.BranchNo and
              daw2.FiscalYear = daw.FiscalYear and
              daw2.FiscalWeek <= daw.FiscalWeek
       ) As cumulative_sales
from [EUUKSQL01].[DASHBOARD].[dbo].[SalesAggregateWeek] daw
where daw.BranchNO in (1, 4, 7) and daw.FiscalYear = 2017;

这假设BranchNo / FiscalYear / FiscalWeek组合在表格中是唯一的(这似乎是一个合理的假设)。