I have a table like this:
---------------------------------------------
|Id | Step | StartedAt |
---------------------------------------------
| 1 | Download Data | 10:20:00 |
| 2 | Data Quality Control | 10:45:00 |
| 3 | Run Prediction | 10:47:00 |
---------------------------------------------
What’s a SQL query that tells me time per each step like this: “Download Data” took 25 minutes, “Data Quality Control” took 2 minutes etc.
Cheers.
P.S My RDBMS is MySQL. Is there any way to do this in MySQL ?
You should use
datetimeortimestampinstead oftimeto make this work across date boundaries. See comments.Standard SQL for most RDBMS
Use a window function for this. Implemented in most notable RDBMS (except MySQL) by now:
lead()retrieves the value of the next row according to the order in theORDER BYclause. For the last row, where you have no "next" row, you getNULL.I quote the manual of PostgreSQL on window functions, since you did not name your RDBMS.
MySQL
In the absence of window functions, one way would be to use correlated subqueries:
Or this is probably faster:
->sqlfiddle with both queries.
The manual about
TIMESTAMPDIFF()orTIMEPDIFF()If your
Idcolumn would be ascending without gaps, this would be simpler. But that’s rarely the case in real life tables.