samedi 14 septembre 2019

How to select record and it's next record based on condition in MySQL workbench?

Say I have application records with application stages (in review, approved, declined, withdrawn, action needed) and I want to only keep records with 'in review' and the next following stage. Some application might only has one in review stage, but some will have multiple 'in review' stages and I would like to keep all of them and their following next record.

My problem is I don't know how to fetch previous and next record based on condition using MySQL workbench. (I can't use rank over and partition function using workbench) I have tried to number my rows but I can only number '1' to 'in review' and everything else became 2 which is not the way I wanted.

Here is an example of my records

id    application id       stage                 time
1         111            in review              2019-08-22 19:40:21
2         111            action needed          2019-08-22 19:40:29
3         111            in review              2019-08-22 19:40:23
4         111            approved               2019-08-22 19:44:23
5         111            declined               2019-08-23 19:40:23       <- I don't need this 'declined' stage since it's not the following stage after an 'in review' one
6         22             in review              2019-09-02 10:00:23
7         22             approved               2019-09-02 22:40:23
8         7788           in review              2019-08-22 19:41:23
9         7788           approved               2019-08-22 19:44:23
10        7788           withdrawn              2019-09-11 08:40:23       <- I don't need this 'withdrawn' stage since it's not the following stage after an 'in review' one

Here is the result I want

id    application id       stage                 time                      Rank
1         111            in review              2019-08-22 19:40:21          1
2         111            action needed          2019-08-22 19:40:29          1
3         111            in review              2019-08-22 19:40:23          2
4         111            approved               2019-08-22 19:44:23          2
6         22             in review              2019-09-02 10:00:23          1
7         22             approved               2019-09-02 22:40:23          1
8         7788           in review              2019-08-22 19:41:23          1
9         7788           approved               2019-08-22 19:44:23          1

I have tried case-when on my own and it's only be able to help me distinguished the case like applciation id in 22 but not other two. Could some please help me with my query?


CASE stage WHEN 'in review' THEN @currentrow:=@rownum+1 ELSE @currentrow+1 END as 'current_row'

Any other tips are also helpful! Thank you so much.

Aucun commentaire:

Enregistrer un commentaire