I have a table of data like this:

```
CommonURN GiftAidAmount GA_Status
14013084 2.00 45
14637494 20.00 45
14637496 1.00 45
14637508 5.00 45
14637520 10.00 45
14637525 19.00 45
14637562 10.00 45
14637586 12.00 45
14637590 3.00 45
14637649 5.00 45

```

I want to group my rows into blocks totalling £1000 or less, where the GA\_Status value equals 45.

What I have so far is this:

```
CREATE TABLE #Temp
(CommonURN int,
GiftAidAmount money,
RunningSum money,
GroupID int);

WITH cte
(commonURN,giftAidAmount,running_sum)
AS
(SELECT
c.commonURN,
c.giftAidAmount,
        (select sum(c2.giftAidAmount)
        from dbo.[Campaign_Data] as c2 
        where 
            GA_Status = 45 and
            c2.commonURN <= c.commonURN)
FROM 
    [dbo].[Campaign_Data] c
WHERE GA_Status = 45)

INSERT INTO #Temp (CommonURN,GiftAidAmount,RunningSum,GroupID)
SELECT 
    commonURN,
    giftAidAmount, 
    running_sum,
    ceiling(running_sum/1000) as GroupID
FROM 
    cte 
ORDER BY
    commonURN

SELECT
    GroupID,
    COUNT(*) NumRows,
    SUM(GiftAidAmount) TotalGiftAid
FROM
    #Temp
GROUP BY GroupID

```

This works pretty well except that one of the groups in the result set is over £1000:

```
GroupID NumRows TotalGiftAid
1   100 999.83
2   107 999.57
3   91  990.82
4   114 1009.34
5   114 995.40
6   58  455.65

```

I don't understand why this is. Can anyone explain and help me fix it? Or suggest a better approach altogther?