My data looks something like this

```
ProductNumber | YearMonth | Number
1               201803      1
1               201804      3
1               201810      6
2               201807      -3
2               201809      5

```

Now what I want to have is add an additional entry "6MSum" which is the sum of the last 6 months per ProductNumber (not the last 6 entries).
Please be aware the YearMonth data is not complete, for every ProductNumber there are gaps in between so I cant just use the last 6 entries for the sum. The final result should look something like this.

```
ProductNumber | YearMonth | Number | 6MSum
1               201803      1        1
1               201804      3        4
1               201810      6        9
2               201807      -3       -3
2               201809      5        2

```

Additionally I don't want to insert the sum to the table but instead use it in a query like:

```
SELECT [ProductNumber],[YearMonth],[Number],
6MSum = CONVERT(INT,SUM...)
FROM ...

```

I found a lot off solutions that use a "sum over period" but only for the last X entries and not for the actual conditional statement of "YearMonth within last 6 months".

Any help would be much appreciated!

**Its a SQL Database**

**EDIT/Answer**

It seems to be the case that the gaps within the months have to be filled with data, afterwards something like

```
sum(Number) OVER (PARTITION BY category 
                      ORDER BY year, week 
                          ROWS 6 PRECEDING) AS 6MSum

```

Should work.

Reference to the solution : <https://dba.stackexchange.com/questions/181773/sum-of-previous-n-number-of-columns-based-on-some-category>