Jump to content

Sub group id


duncan121

Recommended Posts

Hi all,

 

I am trying to add a grouping id when I select the table but a loss how to do it.

 

Any ideas?

 

Thanks so much

 

 

New id Pupil name 1 John Smith 1 John Smith 1 John Smith 1 John Smith 2 Jenny Wills 2 Jenny Wills 2 Jenny Wills 3 Mark Long 3 Mark Long 3 Mark Long

 

 

Link to comment
Share on other sites

OK. I'll assume we're starting with something like this:

mysql> select * from duncan;
+----+-------------+--------+
| id | pupil_name  | new_id |
+----+-------------+--------+
|  1 | John Smith  |   NULL |
|  2 | Jenny Wills |   NULL |
|  3 | Jenny Wills |   NULL |
|  4 | John Smith  |   NULL |
|  5 | Jenny Wills |   NULL |
|  6 | Mark Long   |   NULL |
|  7 | John Smith  |   NULL |
|  8 | Mark Long   |   NULL |
|  9 | John Smith  |   NULL |
+----+-------------+--------+

Then

UPDATE duncan
JOIN
    (
    SELECT 
        @grp := IF(pupil_name=@prev, @grp, @grp+1) as groupid,
        @prev:= pupil_name as pupil_name
        FROM duncan
            JOIN(SELECT @prev:='', @grp:=0) as init
        ORDER BY pupil_name
    ) as grpcalc USING (pupil_name)
SET duncan.new_id = grpcalc.groupid

Results in

mysql> select * from duncan order by pupil_name;
+----+-------------+--------+
| id | pupil_name  | new_id |
+----+-------------+--------+
|  2 | Jenny Wills |      1 |
|  3 | Jenny Wills |      1 |
|  5 | Jenny Wills |      1 |
|  1 | John Smith  |      2 |
|  4 | John Smith  |      2 |
|  7 | John Smith  |      2 |
|  9 | John Smith  |      2 |
|  6 | Mark Long   |      3 |
|  8 | Mark Long   |      3 |
+----+-------------+--------+
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.