There is a jobs
table,
jobID | state | timestamp |
---|---|---|
1 | inProgress | 2023-11-02 10:39:37 |
1 | some random log | 2023-11-02 10:40:37 |
2 | inProgress | 2023-11-02 10:43:37 |
1 | inProgress | 2023-11-02 10:44:37 |
1 | inProgress | 2023-11-02 10:45:37 |
1 | inProgress | 2023-11-02 10:50:00 |
1 | end | 2023-11-02 11:40:37 |
1 | inProgress | 2023-11-02 11:43:37 |
1 | inProgress | 2023-11-02 11:44:37 |
1 | end | 2023-11-02 11:45:37 |
2 | some random log | 2023-11-02 11:50:37 |
2 | end | 2023-11-02 12:00:37 |
I would like to
- calculate how many jobs are in progress (i.e. has already started but not end yet)
I first thought I could calculate count(state=inProgress)-count(state=end)
to get the number of inProgress jobs but inProgress
could show up not only once.
- get execution duration for each finished job
Note that a job can execute multiple times, exg. jobID1
executed from start to finish twice, therefore two execution durations need to be calculated for jobID1
.
jobID1
execution duration is time diff between 2023-11-02 11:40:37, 2023-11-02 10:39:37
AND time diff between 2023-11-02 11:45:37, 2023-11-02 11:43:37
jobID2
execution duration is time diff between 2023-11-02 12:00:37, 2023-11-02 10:43:37
2
Answers
To count the number of jobs that are in progress (started but not yet finished):
To calculate the execution duration for each finished job:
For a job that may have multiple instances the following approach "looks backward" to locate any previous ends for the same jobid, each instance of the jobid is also assigned using
row_number()
. Then these rows for "ends" are then joined to any rows representing "In Progress" with conditions to ensure they fit within "previous end" (or NULL) and "this end". Then the minimum start of each job instance is calculated, and the duration (in seconds) also made available.See fiddle
Once you have the jobs and instances of them available, the min/max start/end and total duration can be easily calculated from the result seen above (optionally the max(job_inst) could also be displayed).