I have a table with three columns: job_id, part, and time, which represent the ID of a shop job, the part manufactured in that job, and the time taken for that job, respectively.
Job_id | Part | Time |
---|---|---|
1 | A | 0 |
2 | F | 0 |
3 | F | 0 |
4 | C | 10 |
5 | B | 0 |
6 | D | 5 |
7 | F | 0 |
8 | B | 0 |
9 | E | 0 |
10 | F | 10 |
In this table, a higher job_id corresponds to a more recent job. For example, for Part F, job_id = 10 represents the most recent job, while job_id = 2 is the oldest.
I need to select all the rows for a part where the most recent job (i.e., the row with the highest job_id) has a ‘time’ of 0. For instance:
Part A: Select it because its most recent job (job_id = 1) has time = 0.
Part B: Select both rows because its most recent job (job_id = 8) has time = 0.
Part F: Do not select any rows because its most recent job (job_id = 10) does not have time = 0.
Desired result:
Job_id | Part | Time |
---|---|---|
1 | A | 0 |
8 | B | 0 |
5 | B | 0 |
9 | E | 0 |
Since we’re selecting rows from different parts based on their most recent job’s time, I believe I need to partition the data by part. To achieve this, I have used the ROW_NUMBER() function to assign row numbers to each group.
Job_id | Part | Time | row_number |
---|---|---|---|
1 | A | 0 | 1 |
8 | B | 0 | 1 |
5 | B | 0 | 2 |
4 | C | 10 | 1 |
6 | D | 5 | 1 |
9 | E | 0 | 1 |
10 | F | 10 | 1 |
7 | F | 0 | 2 |
3 | F | 0 | 3 |
2 | F | 0 | 4 |
However, I am unsure how to use this partitioned data to extract the desired result.
I am using MySQL for this task.
2
Answers
Please try this one. I tired my best to implement the suggested solution
fiddle
PS. Thanks to Sergey for source script.