3


I have the following table in my SQL Server 2012 instance:

+---------+---------+
| Quarter | Values  |
+---------+---------+
| Q1      | 10      |
| Q2      | 15      |
| Q3      |  5      |
| Q4      |  1      |
+---------+---------+

I would like grouping quarter in order to sum values to obtain
Q1 = 25
Q2 = 31
So, Q2 sum also previous values that exist in Q1. If I had Q3 the sum would be Sum(Q1) + Sum (Q2) + Sum (Q3).
In this way a simple Group by clause doesn't work. Can anybody help me to find a solution in order to perform the described task using a simple select statement without using Union, please?

4

2 回答 2

2

由于您使用的是 SQL 2012,因此您也可以使用RANGES

SELECT DISTINCT
  TheQuarter
  , SUM( TheValue ) OVER ( ORDER BY TheQuarter RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS "RollingSum"
FROM 
  MyData

SQL小提琴

@编辑:

如果您要处理多年,请参阅this fiddle

于 2012-12-19T01:35:27.297 回答
1

请注意,如果您处理多年,您可能需要更改此查询。

--Setup sample table
DECLARE @MyData TABLE (
    TheQuarter VARCHAR(2) NOT NULL,
    TheValue INT NOT NULL
);

--insert sample data
INSERT INTO @MyData VALUES ('Q1',10),
    ('Q1',15),
    ('Q2',5),
    ('Q2',1);

WITH Totals AS (SELECT ROW_NUMBER() OVER (ORDER BY TheQuarter ASC) AS [QuarterIndex],
            TheQuarter, SUM(TheValue) AS [TotalValue]
        FROM @MyData GROUP BY TheQuarter)
    SELECT t.TheQuarter, SUM(tPlusPrev.TotalValue) AS [TotalValue]
    FROM Totals t
        LEFT OUTER JOIN Totals tPlusPrev ON t.QuarterIndex >= tPlusPrev.QuarterIndex
    GROUP BY t.TheQuarter;
于 2012-12-18T17:25:55.383 回答