T / SQL - 如何选择具有最大总和的前10行(或更少)行

时间:2012-08-30 08:04:28

标签: tsql

我需要使用SUM(FileSize)<选择10行或更少的行。 1000000.需要通过AttachmentId订购结果。假设如果单个FileSize超出限制,则可以选择该行(而不是其他行)。

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

表格是:

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

请帮忙。

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

更新即可。非常感谢Nikola。我们到了那里,但是当第一行超过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  

解决方案即可。这是斯图尔特的代码(稍加修改),我接受了答案。非常感谢斯图尔特!:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

SELECT TOP 10 AttachmentId
FROM Attachment
GROUP BY AttachmentId
HAVING SUM(FileSize) < 1000000
ORDER BY AttachmentId