【问题标题】:Rollover sum with grouping in SQL Server在 SQL Server 中进行分组的翻转总和
【发布时间】:2014-11-30 15:25:20
【问题描述】:

我需要在 SQL Server 中使用分组进行翻转总和

我需要为下一个季度计算同一年内的销售额。

数据如下图

年度季度销售额

2011         1        10

2011         2        5

2011         5        30

2012         4        30

2012         5        2

我需要如下输出

年份 |季|今年的销售到现在

2011 年 1 月 10 日

2011 2 15(即同年上一季度的 10 + 5)

2011 5 45(今年前几个季度的 10 + 5 + 30)

2012 4 30

2012 4 32(30 + 2,即今年上一季度的 30)

【问题讨论】:

标签: sql-server sql-server-2008 sql-server-2012


【解决方案1】:

有很多方法可以实现Rolling Sum。这里有几个选项。

CREATE TABLE #test
  (years INT, id INT, sal INT )

INSERT #test
VALUES (2011,1,10),
       (2011,2,5),
       (2011,5,30),
       (2012,4,30),
       (2012,5,2)

方法一:使用Correlated Sub-Query

SELECT *,
       (SELECT Sum(sal)
        FROM   #test b
        WHERE  a.years = b.years
               AND a.id >= b.id)
FROM   #test a

方法二:使用Inner Join

SELECT a.years,
       a.id,
       Sum(b.sal) AS total
FROM   #test a
       INNER JOIN #test b
               ON a.id >= b.id
                  AND a.years = b.years
GROUP  BY a.years,
          a.id 

方法 3: 使用 SUM()OVER() clauseCheck here 了解更多关于 Over Clause 的信息

SQL FIDDLE DEMO

SELECT a.years,
       a.id,
       sal,
       Sum(sal)
         OVER(
           partition BY years
           ORDER BY id rows UNBOUNDED PRECEDING) AS runningtotal
FROM   #test 

注意: Method 3 解决方案适用于 SQL SERVER 2012+

【讨论】:

  • @NoDisplayName 感谢您提供详细的解决方案。我已将您的 Method3 修改为“按部门分区,年”,因为我将分组类别添加为部门明智。我说的对吗?
【解决方案2】:
create table test(year1 int,quarter1 int,sales int)

insert into test
select 2011         ,1        ,10 UNION ALL

select 2011         ,2        ,5 UNION ALL

select 2011         ,5        ,30 UNION ALL

select 2012         ,4        ,30 UNION ALL

select 2012         ,5        ,2 

试试这个:

 SELECT a.year1
           , a.quarter1
           , SUM(b.sales) AS total

FROM test a INNER JOIN test b
     ON  a.quarter1 >= b.quarter1
     AND a.year1 = b.year1

GROUP BY a.year1
           , a.quarter1
ORDER BY a.year1

输出

2011    1   10
2011    2   15
2011    5   45
2012    4   30
2012    5   32

【讨论】:

    【解决方案3】:

    尝试使用sum() with Partition By

    select *,sum(sales)over(partition by Year order by Year) as salestillnowthis  from table 
    

    More Info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多