I have two tables:
-
things
:+------+----------------+------------+ | id | current_status | created_at | +------+----------------+------------+ | 7770 | active | 2016-08-09 | +------+----------------+------------+
-
thing_status_tract
:+----------+-------------+-----------+---------------------+ | thing_id | status_from | status_to | changed_at | +----------+-------------+-----------+---------------------+ | 7770 | incomplete | inactive | 2016-08-09 16:26:22 | | 7770 | inactive | active | 2016-08-10 12:31:04 | +----------+-------------+-----------+---------------------+
I need data in the following form. This table has a status and its corresponding start and end timestamp for a particular thing_id
:
+----------+-------------+---------------------+---------------------+
| thing_id | status | status_start_date | status_end_date |
+----------+-------------+---------------------+---------------------+
| 7770 | incomplete | 2016-08-09 00:00:00 | 2016-08-09 16:26:22 |
| 7770 | inactive | 2016-08-09 16:26:22 | 2016-08-10 12:31:04 |
| 7770 | active | 2016-08-10 12:31:04 | now() |
+----------+-------------+---------------------+---------------------+
How to do that with a SQL query?
Best Answer
Of course, my previous answer was just to answer your immediate question. As I mentioned in my comments, your data model itself is flawed. Not only should you not keep both 'status_from' (prevous_status) and 'status_to' in the history table, you should also NOT keep status at all in the THINGS table. This violates standard data normalization rules.
What you should do is drop status from the THINGS table, establish a FK relationship between the two tables, and use a proper query to derive the current status when needed.
First, create and populate the THINGS table. I've added a couple of columns just to indicate the kinds of things that should be in this table:
S
Then create and populate the history tracking table:
And your history report (as before)
And your current status report