使用 SQL 2008/2012 计算状态之间的时间范围
我有下表存储学生的状态
+----+-----------+------------------+---------+---------+
| ID | PERSON_ID | TIMESTAMP | IN_HOME | STUDYNG |
+----+-----------+------------------+---------+---------+
| 1 | 1 | 17/10/2012 19:00 | 0 | 0 |
| 2 | 1 | 17/10/2012 19:02 | 1 | 0 |
| 3 | 1 | 17/10/2012 19:03 | 1 | 1 |
| 4 | 1 | 17/10/2012 19:04 | 1 | 1 |
| 5 | 1 | 17/10/2012 19:05 | 1 | 0 |
| 6 | 1 | 17/10/2012 19:10 | 0 | 0 |
| 7 | 1 | 17/10/2012 19:12 | 0 | 0 |
| 8 | 1 | 17/10/2012 19:20 | 1 | 0 |
| 9 | 1 | 17/10/2012 19:25 | 1 | 0 |
| 10 | 1 | 17/10/2012 19:26 | 1 | 1 |
| 11 | 1 | 17/10/2012 19:30 | 1 | 0 |
+----+-----------+------------------+---------+---------+
我想以两种方式产生结果来制作一些报告:
一世:
+-----------+------------------+------------------+---------+---------+
| PERSON_ID | START | END | IN_HOME | STUDYNG |
+-----------+------------------+------------------+---------+---------+
| 1 | 17/10/2012 19:00 | 17/10/2012 19:02 | 0 | 0 |
| 1 | 17/10/2012 19:02 | 17/10/2012 19:03 | 1 | 0 |
| 1 | 17/10/2012 19:03 | 17/10/2012 19:05 | 1 | 1 |
| 1 | 17/10/2012 19:05 | 17/10/2012 19:10 | 1 | 0 |
| 1 | 17/10/2012 19:10 | 17/10/2012 19:20 | 0 | 0 |
| 1 | 17/10/2012 19:20 | 17/10/2012 19:26 | 1 | 0 |
| 1 | 17/10/2012 19:26 | 17/10/2012 19:30 | 1 | 1 |
+-----------+------------------+------------------+---------+---------+
二:
+-----+------------------+------------------+--------+---------+----------+----------+
| PID | START | END | InHOME | TotTIME | FreeTIME | StudTIME |
+-----+------------------+------------------+--------+---------+----------+----------+
| 1 | 17/10/2012 19:00 | 17/10/2012 19:02 | 0 | 2min | 2min | 0min |
| 1 | 17/10/2012 19:02 | 17/10/2012 19:10 | 1 | 8min | 6min | 2min |
| 1 | 17/10/2012 19:10 | 17/10/2012 19:20 | 0 | 10min | 10min | 0min |
| 1 | 17/10/2012 19:20 | 17/10/2012 19:26 | 1 | 6min | 6min | 0min |
+-----+------------------+------------------+--------+---------+----------+----------+
解决这个问题的最佳解决方案是什么?