-4

我需要选择 SUM(FileSize) < 1000000 的 10 行或更少的行。结果需要按 AttachmentId 排序。假设如果单个 FileSize 超过限制,那么只选择该行(而不是其他行)就可以了。

理想情况下,我希望它只是一个没有更多语句的选择查询。

表格是:

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

请帮忙。

更新。很遗憾听到大多数读者不清楚这些要求。不需要进行任何分组。我需要得到的只是前 10 行或更少。如果它们在 FileSize 上的总数超过 1000000,它将小于 10。如果其 FileSize 等于或大于 1000000,它将只有 1 行。服务器是 SQL 2008。

更新。非常感谢尼古拉。我们已经到了那里,但我仍然不确定如何实现第一行超过 FileSize 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  

解决方案。这是来自 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
4

2 回答 2

2

也许这会让你开始:

BEGIN TRAN

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


INSERT  INTO Attachment
        SELECT  1
              , 10
        UNION
        SELECT  2
              , 20
        UNION
        SELECT  3
              , 30

--values to exceed
DECLARE @p INT = 50

--row count to restrict to
DECLARE @r INT = 10

;
WITH    CTE
          AS ( SELECT   AttachmentID
                      , FileSize
                      , RunningID = ROW_NUMBER() OVER ( ORDER BY FileSize DESC )
               FROM     Attachment
             )
    SELECT TOP ( @r )
            AttachmentID
          , FileSize
    FROM    CTE AS A
    WHERE   ( SELECT    SUM(FileSize)
              FROM      CTE
              WHERE     RunningID <= A.RunningID
            ) <= @p 
OR A.RunningID = 1



ROLLBACK
于 2012-08-31T01:30:55.780 回答
1
SELECT TOP 10 AttachmentId
FROM Attachment
GROUP BY AttachmentId
HAVING SUM(FileSize) < 1000000
ORDER BY AttachmentId
于 2012-08-30T08:44:48.833 回答