I am working with a database that includes a history table showing when projects have moved to the next state of development. Here is some example data.
dbo.history_table
| ProjectID | State | Timestamp |
| 1 | 1 | 2018-03-22 10:38:27.000 |
| 1 | 2 | 2018-03-23 10:22:56.000 |
| 1 | 3 | 2018-03-24 12:18:32.000 |
| 2 | 1 | 2018-03-24 11:01:17.000 |
| 1 | 4 | 2018-03-25 10:32:41.000 |
| 2 | 4 | 2018-03-26 12:39:03.000 |
There are a number of states that look something like this:
| State # | Description | Notes
| State 1 | Planning |
| State 2 | Pre-Production |
| State 3 | Production |
| State 4 | Post-Production |
| State 5 | Successful | Terminal state
| State 6 | Unsuccessful | Terminal state
| State 7 | Cancelled | Terminal state
These states are roughly sequential, but not quite, and not always. For instance, each project can only end in one of the three terminal states. Furthermore, although all projects begin in State 1, not all projects hit all states before terminating.
I need to write a query that looks at a particular state and shows the next state those records move to. The data I need from this query would look something like this:
Report: State 2 Pipeline
| Total: | 100 |
| Moved to State 3: | 50 |
| Moved to State 4: | 0 |
| Moved to State 5: | 25 |
| Moved to State 6: | 0 |
| Moved to State 7: | 25 |