SQL Group By Modulo of Row Count

Posted by Alex Czarto on Stack Overflow See other posts from Stack Overflow or by Alex Czarto
Published on 2010-04-01T15:34:09Z Indexed on 2010/04/01 15:43 UTC
Read the original article Hit count: 386

Filed under:
|
|

I have the following sample data:

Id     Name     Quantity
1      Red      1
2      Red      3
3      Blue     1
4      Red      1
5      Yellow   3

So for this example, there are a total of 5 Red, 1 Blue, and 3 Yellow. I am looking for a way to group them by Color, but with a maximum of 2 items per group (sorting is not important). Like so:

Name     QuantityInPackage
Red      2
Red      2
Red      1
Blue     1
Yellow   2
Yellow   1

Any suggestions on how to accomplish this using T-SQL on MS-SQL 2005?

© Stack Overflow or respective owner

Related posts about sql

Related posts about tsql