I need to select 10 or less rows with the SUM(FileSize) < 1000000. Results need to be ordered by AttachmentId. Let's say that if a single FileSize exceeds the limit it's okay just for that row (and no other) to be selected.

Ideally I'd like it to be just a select query with no more statements.

The table is:

```
CREATE TABLE [Attachment](
    [AttachmentId] [int] NOT NULL,
    [FileSize] [int] NOT NULL
)

```

Please help.

**Updated**. Sorry to hear that the requirements are unclear for most of the readers. There is no requirement to do any grouping. All I need to get is just plain first 10 rows or less. It will be less than 10 if their total on FileSize exceeds 1000000. It will be only 1 row if its FileSize equals 1000000 or more. The server is SQL 2008.

**Updated**. Many thanks to Nikola. We are getting there, but I'm still not sure how to implement the case when the first row exceeds FileSize of 1000000. 

```
SELECT TOP 10 a.AttachmentId, rt.runningTotal 
FROM Attachment a
CROSS APPLY (SELECT SUM(aa.FileSize) AS runningTotal
   FROM Attachment aa
   WHERE aa.AttachmentId <= a.AttachmentId
) AS rt
GROUP BY a.AttachmentId, rt.runningTotal
HAVING rt.runningTotal < 1000000
ORDER BY a.AttachmentId  

```

**Solution**. This is the code (slightly modified) from Stuart which I accept as answer. Many thanks to Stuart!:

```
WITH CTE
  AS ( SELECT TOP 10 AttachmentId, FileSize
, RunningID = ROW_NUMBER() OVER (ORDER BY AttachmentId)
   FROM Attachment
  )
SELECT AttachmentId, FileSize
FROM CTE AS a
WHERE (SELECT SUM(FileSize)
       FROM CTE
       WHERE RunningID <= a.RunningID
       ) <= 10000000
       OR a.RunningID = 1

```