Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 860039
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T08:45:33+00:00 2026-05-15T08:45:33+00:00

I need to group a set of rows based on the Category column, and

  • 0

I need to group a set of rows based on the Category column, and also limit the combined rows based on the SUM(Number) column to be less than or equal to the @Limit value.

For each distinct Category column I need to identify “buckets” that are <=@limit. If the SUM(Number) of all the rows for a Category column are <=@Limit then there will be only 1 bucket for that Category value (like ‘CCCC’ in the sample data). However if the SUM(Number)>@limit, then there will be multiple bucket rows for that Category value (like ‘AAAA’ in the sample data), and each bucket must be <=@Limit. There can be as many buckets as necessary. Also, look at Category value ‘DDDD’, its one row is greater than @Limit all by itself, and gets split into two rows in the result set.

Given this simplified data:

DECLARE @Detail table (DetailID int  primary key, Category char(4), Number int)
SET NOCOUNT ON
INSERT @Detail VALUES ( 1, 'AAAA',100)
INSERT @Detail VALUES ( 2, 'AAAA', 50)
INSERT @Detail VALUES ( 3, 'AAAA',300)
INSERT @Detail VALUES ( 4, 'AAAA',200)
INSERT @Detail VALUES ( 5, 'BBBB',500)
INSERT @Detail VALUES ( 6, 'CCCC',200)
INSERT @Detail VALUES ( 7, 'CCCC',100)
INSERT @Detail VALUES ( 8, 'CCCC', 50)
INSERT @Detail VALUES ( 9, 'DDDD',800)
INSERT @Detail VALUES (10, 'EEEE',100)
INSERT @Detail VALUES (11, 'AAAA',200) --EDIT added
INSERT @Detail VALUES (12, 'AAAA',200) --EDIT added
INSERT @Detail VALUES (13, 'AAAA',200) --EDIT added
INSERT @Detail VALUES (14, 'AAAA',200) --EDIT added
SET NOCOUNT OFF

DECLARE @Limit int
SET @Limit=500

I need one of these result set:

DetailID  Bucket  |    DetailID  Category Bucket
--------  ------  |    --------  -------- ------
 1        1       |     1        'AAAA'   1     
 2        1       |     2        'AAAA'   1     
 3        1       |     3        'AAAA'   1     
 4        2       |     4        'AAAA'   2     
11        2       |    11        'AAAA'   2      --EDIT added
12        3       |    12        'AAAA'   3      --EDIT added
13        3       |    13        'AAAA'   3      --EDIT added
14        4       |    14        'AAAA'   4      --EDIT added
 5        5       OR    5        'BBBB'   1     
 6        6       |     6        'CCCC'   1     
 7        6       |     7        'CCCC'   1     
 8        6       |     8        'CCCC'   1     
 9        7       |     9        'DDDD'   1     
 9        8       |     9        'DDDD'   2     
10        9       |    10        'EEEE'   1   

EDIT after trying out all the answers

With all attempts at a set based solution not working as needed, I’m going with a modification to @GalacticJello Answer, modification noted in the code below. I basically find all the rows where the entire category fits into the bucket and INSERT them using a single INSERT-SELECT, and then loop over the remaining data using @GalacticJello cursor free loop. This will work fine in my situation since there will hardly ever be any rows processed by the loop.

DECLARE @DetailTemp table (PID INT IDENTITY(1,1), DetailID int  primary key, Category char(4), Number int) 
DECLARE @DetailFinal table (DetailID int, Category char(4), Bucket int) ---<<<renamed column to Bucket

DECLARE @DetailCount int
SET @DetailCount = 0;

--------<<<optimization added starts here
;WITH AllSingleBuckets AS (
    SELECT
        Category
        FROM @Detail
        GROUP BY Category
        HAVING SUM(Number)<=@Limit

)
INSERT INTO @DetailFinal
        (DetailID, Category, Bucket)
    SELECT
        d.DetailID,d.Category,1
        FROM @Detail                    d
            INNER JOIN AllSingleBuckets s ON d.Category=s.Category
--------<<<optimization added ends here

INSERT @DetailTemp
--------<<<changed for optimization, added WHERE clause
SELECT d.DetailId, d.Category, d.Number FROM @Detail d WHERE NOT EXISTS (SELECT 1 FROM @DetailFinal f WHERE d.Category=f.Category) ORDER BY Category, DetailId
SELECT @DetailCount = @@ROWCOUNT

DECLARE @CurrentPid int
SET @CurrentPid = 1

DECLARE @ThisId int
DECLARE @ThisCategory char(4)
DECLARE @ThisNumber int

DECLARE @CurrentCategory char(4)
DECLARE @CurrentSum INT
DECLARE @CurrentBucket INT


WHILE @CurrentPid <= @DetailCount
BEGIN
    SELECT @ThisId = DetailId, @ThisCategory = Category, @ThisNumber = Number
    FROM @DetailTemp 
    WHERE PID = @CurrentPid

    IF @ThisCategory = @CurrentCategory
    BEGIN
        IF @CurrentSum + @ThisNumber > @Limit
        BEGIN
            SET @CurrentBucket = @CurrentBucket + 1
            SET @CurrentSum = @ThisNumber
        END
        ELSE
        BEGIN
            SET @CurrentSum = @CurrentSum + @ThisNumber
        END
    END
    ELSE
    BEGIN
        SET @CurrentBucket = 1
        SET @CurrentCategory = @ThisCategory
        SET @CurrentSum = @ThisNumber
    END

    WHILE @CurrentSum > @Limit
    BEGIN
        INSERT @DetailFinal SELECT @ThisId, @CurrentCategory, @CurrentBucket
        SET @CurrentBucket = @CurrentBucket + 1
        SET @CurrentSum = @CurrentSum - @Limit
    END

    INSERT @DetailFinal SELECT @ThisId, @CurrentCategory, @CurrentBucket

    SET @CurrentPid = @CurrentPid + 1
END


SELECT * from @DetailFinal ORDER BY Category --------<<<added order by

OUTPUT:

DetailID    Category Bucket
----------- -------- -----------
1           AAAA     1
2           AAAA     1
3           AAAA     1
4           AAAA     2
11          AAAA     2
12          AAAA     3
13          AAAA     3
14          AAAA     4
5           BBBB     1
6           CCCC     1
7           CCCC     1
8           CCCC     1
9           DDDD     1
9           DDDD     2
10          EEEE     1

(15 row(s) affected)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T08:45:33+00:00Added an answer on May 15, 2026 at 8:45 am
    DECLARE @Detail table (DetailID int  primary key, Category char(4), Number int) 
    SET NOCOUNT ON 
    INSERT @Detail VALUES ( 1, 'AAAA',100) 
    INSERT @Detail VALUES ( 2, 'AAAA', 50) 
    INSERT @Detail VALUES ( 3, 'AAAA',300) 
    INSERT @Detail VALUES ( 4, 'AAAA',200) 
    INSERT @Detail VALUES ( 5, 'BBBB',500) 
    INSERT @Detail VALUES ( 6, 'CCCC',200) 
    INSERT @Detail VALUES ( 7, 'CCCC',100) 
    INSERT @Detail VALUES ( 8, 'CCCC', 50) 
    INSERT @Detail VALUES ( 9, 'DDDD',800) 
    INSERT @Detail VALUES (10, 'EEEE',100) 
    INSERT @Detail VALUES (11, 'AAAA',200) --EDIT added 
    INSERT @Detail VALUES (12, 'AAAA',200) --EDIT added 
    INSERT @Detail VALUES (13, 'AAAA',200) --EDIT added 
    INSERT @Detail VALUES (14, 'AAAA',200) --EDIT added 
    SET NOCOUNT OFF 
    
    DECLARE @Limit int 
    SET @Limit=500 
    
    DECLARE @DetailTemp table (PID INT IDENTITY(1,1), DetailID int  primary key, Category char(4), Number int) 
    DECLARE @DetailFinal table (DetailID int, Category char(4), Number int) 
    
    DECLARE @DetailCount int
    SET @DetailCount = 0;
    
    INSERT @DetailTemp
    SELECT DetailId, Category, Number FROM @Detail ORDER BY Category, DetailId
    SELECT @DetailCount = @@ROWCOUNT
    
    DECLARE @CurrentPid int
    SET @CurrentPid = 1
    
    DECLARE @ThisId int
    DECLARE @ThisCategory char(4)
    DECLARE @ThisNumber int
    
    DECLARE @CurrentCategory char(4)
    DECLARE @CurrentSum INT
    DECLARE @CurrentBucket INT
    
    
    WHILE @CurrentPid <= @DetailCount
    BEGIN
        SELECT @ThisId = DetailId, @ThisCategory = Category, @ThisNumber = Number
        FROM @DetailTemp 
        WHERE PID = @CurrentPid
    
        IF @ThisCategory = @CurrentCategory
        BEGIN
            IF @CurrentSum + @ThisNumber > @Limit
            BEGIN
                SET @CurrentBucket = @CurrentBucket + 1
                SET @CurrentSum = @ThisNumber
            END
            ELSE
            BEGIN
                SET @CurrentSum = @CurrentSum + @ThisNumber
            END
        END
        ELSE
        BEGIN
            SET @CurrentBucket = 1
            SET @CurrentCategory = @ThisCategory
            SET @CurrentSum = @ThisNumber
        END
    
        WHILE @CurrentSum > @Limit
        BEGIN
            INSERT @DetailFinal SELECT @ThisId, @CurrentCategory, @CurrentBucket
            SET @CurrentBucket = @CurrentBucket + 1
            SET @CurrentSum = @CurrentSum - @Limit
    END
    
        INSERT @DetailFinal SELECT @ThisId, @CurrentCategory, @CurrentBucket
    
        SET @CurrentPid = @CurrentPid + 1
    END
    
    
    SELECT * from @DetailFinal
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Following is the sample data set that I need to group together, if you
Given the XML below, I need to group by InputItem and sum the costs
I have a active report and I need to group it on my country
Anyone know what group I need to belong to show up in the sp_help_operator
I need to update a group of cells by inserting the same two characters
I need to grant rights to Windows user group Everyone to the HKCR hive
I need add a new user group for mediawiki. The new group has more
I have a need to determine what security group(s) a user is a member
I need to send email notifications to either a group or user on every
Let's say I need to have the ratio of "number of items available from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.