0

I am still relatively new to MySQL and am stuck on a bit of data engineering.

I have a table with following:

Event_ID, Minutes, EventCode

I have multiple rows with same Event_ID and what event has occurred (eventcode) along with when in minutes (Minutes).

What I want to do is output to a new table the sequence of events based on the minutes for an event_id:

Eg:

Source:

Event_ID,   Minutes, EventCode
12,         45,         A
12,         49,         B
12,         78,         A

WOuld be transformed into:

12, 45, A, 1
12, 49, B, 2
12, 78, B, 3

So the last column shows the sequence. Although it can be assmed the source table is sorted by event_id following by minutes I would rather a solution that worked for it to be unsorted if possible

Some pointers would be great!

Thanks

3
  • What version of MySQL are you using please Commented Feb 4, 2020 at 12:08
  • 1
    which version are you using, if above 8.0 you can use the row_number() function Commented Feb 4, 2020 at 12:08
  • 2
    if under 8 here is a tutorial on how to emulate row_number() mysqltutorial.org/mysql-row_number Commented Feb 4, 2020 at 12:09

2 Answers 2

3

Im MySQL 8 and higher you can use the row_number() window function.

SELECT event_id,
       minutes,
       eventcode,
       row_number() OVER (PARTITION BY event_id
                          ORDER BY minutes)
       FROM elbat;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this query: select event_id, minutes, eventcode, @rownum:=@rownum+1 No from elbat, (SELECT @rownum:=0) r;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.