Skip to content
Advertisement

Getting SUM of ‘x’ consecutive values where x is an integer from another row

I am trying to code in Microsoft SQL Server Management Studio. This is SQL. I have to get the sum of x previous consecutive rows where x is based on a number in another row. For Example:

enter image description here

Example 1: As you can see in Row 10, the RESULT column returns the SUM of the Quantities of the 4 rows (Row 7 to 10) basing it on the Column ‘Consecutive’, which has the value 4. (7+7+7+9 = 30)

Example 2: In Row 9, the RESULT column returns the SUM of the Quantities in the 2 rows, again based on the Column ‘Consecutive’ which has the value 2. (7+7+7 = 14)

Example 3: In Row 8, the RESULT column returns the SUM of the Quantities in the 3 rows, again based on the Column ‘Consecutive’ which has the value 3. (7+7+1 = 15).

My code looked like this, but I do not know how to replace the ‘Consecutive’ part.

SUM(Quantities) OVER
(   PARTITION BY ...
        ORDER BY ...  ----This is 
        ROWS BETWEEN CURRENT ROW AND Consecutive FOLLOWING

The error says

Incorrect syntax near ‘Consecutive’

Advertisement

Answer

You can simply select the needed rows for each row. Here is full working example:

DECLARE @DataSource TABLE 
(
    [Row] INT
   ,[Quantities] INT
   ,[Consecutive] INT
);

INSERT INTO @DataSource ([Row], [Quantities], [Consecutive])
VALUES (1, 8, 4)
      ,(2, 7, 3)
      ,(3, 7, 3)
      ,(4, 7, 2)
      ,(5, 9, 4)
      ,(6, 1, 3)
      ,(7, 7, 3)
      ,(8, 7, 3)
      ,(9, 7, 2)
      ,(10, 9, 4);

SELECT *
FROM @DataSource E
CROSS APPLY
(
    SELECT SUM(I.[Quantities])
    FROM @DataSource I
    WHERE I.[Row] > = E.[Row] - E.[Consecutive] + 1
        AND I.[Row] <= E.[Row]
) DS ([RESULT]);

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement