0

I need to divide records into groups that have max n elements per group id, I need extra column to be some kind of counter that will increment by one when it reaches certain number of rows. I'm not speaking English native so I've build example code to show what data I have and what results I need.

Here is sqlfiddle: http://sqlfiddle.com/#!3/c9cf5/1

and here is sqlfiddle code:

CREATE TABLE tab1 
    (
     id int
    );

INSERT INTO tab1 (id) VALUES (1)
INSERT INTO tab1 (id) VALUES (2)
INSERT INTO tab1 (id) VALUES (3)
INSERT INTO tab1 (id) VALUES (4)
INSERT INTO tab1 (id) VALUES (5)
INSERT INTO tab1 (id) VALUES (6)
INSERT INTO tab1 (id) VALUES (7)
INSERT INTO tab1 (id) VALUES (8)
INSERT INTO tab1 (id) VALUES (9)
INSERT INTO tab1 (id) VALUES (10)
INSERT INTO tab1 (id) VALUES (11)
INSERT INTO tab1 (id) VALUES (12)
INSERT INTO tab1 (id) VALUES (13)
INSERT INTO tab1 (id) VALUES (14)
INSERT INTO tab1 (id) VALUES (15)
INSERT INTO tab1 (id) VALUES (16)
INSERT INTO tab1 (id) VALUES (17)
INSERT INTO tab1 (id) VALUES (18)
INSERT INTO tab1 (id) VALUES (18)
INSERT INTO tab1 (id) VALUES (20)

SELECT id,
NTILE(4) OVER(ORDER BY id DESC) AS X
from tab1

My table with data looks like this:

 id
 --
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

and I need result that look looks like this:

 id | group
 --
 1 | 1
 2 | 1
 3 | 1
 4 | 1
 5 | 2
 6 | 2
 7 | 2
 8 | 2
 9 | 3
10 | 3

In above example I want to group all records into groups containing max 4 elements, so records 1-4 are in group 1, records 5-8 in group 2 and record 9-10 are in third.

Probably there is build in function that can do this, but because of my English skills I wasn't able to find it.

I've tried counting all elements in table and dividing it by number or elements and then using it in NTILE, but this way I get equal group and that's not result I need.

1
  • it can be achieved through NTILE then what is your main problem lies ??
    – mohan111
    Oct 14, 2015 at 14:07

2 Answers 2

2

You can do this using ROW_NUMBER:

SELECT  id,
        group_id = (ROW_NUMBER() OVER (ORDER BY id) - 1) / 4 + 1
FROM    my_table

This will work even if there are gaps in your id, like 1,2,5,10.

1

Just use row_number() over (order by id), you can just divide the row number for example with 4, then you'll get the number to increase every 4 rows.

SQL Fiddle seems to be broken, so I can't edit your example.

7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.