合并重叠的日期范围以形成时间轴

时间:2017-06-13 14:47:26

标签: sql-server tsql

我有一个数据集,我需要在重叠日期范围内合并,以形成一个时间轴,以指示患者的活动和非活动阶段。我正在寻找一个可以转换这些数据的t-sql脚本。

这是一个样本数据集:

+----------+-------+------------------+----------------+-------------+------------+
| Practice | PatID | AgeAtActiveStart | AgeAtActiveEnd | ActiveStart | ActiveEnd  |
+----------+-------+------------------+----------------+-------------+------------+
| Prac1    | P1    |               58 |             72 | 2003-05-09  | 2017-12-22 |
| Prac1    | P1    |               59 |             60 | 2004-03-30  | 2005-03-30 |
| Prac1    | P1    |               60 |             63 | 2005-12-14  | 2008-04-29 |
| Prac1    | P1    |               63 |             65 | 2008-07-31  | 2010-06-17 |
| Prac1    | P1    |               65 |             68 | 2010-07-30  | 2013-08-07 |
| Prac1    | P1    |               69 |             72 | 2014-03-06  | 2018-01-04 |
| Prac1    | P2    |               32 |             33 | 2004-12-08  | 2006-04-01 |
| Prac1    | P2    |               32 |             33 | 2005-07-18  | 2006-07-18 |
| Prac1    | P2    |               33 |             34 | 2006-11-02  | 2007-11-02 |
| Prac1    | P2    |               36 |             38 | 2009-05-13  | 2011-02-09 |
| Prac1    | P2    |               38 |             39 | 2011-04-07  | 2012-06-16 |
| Prac1    | P2    |               40 |             41 | 2012-12-12  | 2014-11-16 |
| Prac1    | P2    |               41 |             45 | 2014-09-15  | 2017-12-21 |
+----------+-------+------------------+----------------+-------------+------------+

这就是我想要将其转化为的内容。在每个患者的时间表中:

+----------+-------+------------------+----------------+-------------+------------+-----------+
| Practice | PatID | AgeAtActiveStart | AgeAtActiveEnd | ActiveStart | ActiveEnd  |  Status   |
+----------+-------+------------------+----------------+-------------+------------+-----------+
| Prac1    | P1    |               58 |             72 | 2003-05-09  | 2018-01-04 | Active    |
| Prac1    | P2    |               32 |             33 | 2004-12-08  | 2006-07-18 | Active    |
| Prac1    | P2    |               33 |             33 | 2006-07-19  | 2006-11-01 | NotActive |
| Prac1    | P2    |               33 |             34 | 2006-11-02  | 2007-11-02 | Active    |
| Prac1    | P2    |               34 |             36 | 2007-11-03  | 2009-05-12 | NotActive |
| Prac1    | P2    |               36 |             38 | 2009-05-13  | 2011-02-09 | Active    |
| Prac1    | P2    |               38 |             38 | 2011-02-10  | 2011-04-06 | NotActive |
| Prac1    | P2    |               38 |             39 | 2011-04-07  | 2012-06-16 | Active    |
| Prac1    | P2    |               39 |             40 | 2012-06-17  | 2012-12-11 | NotActive |
| Prac1    | P2    |               40 |             45 | 2012-12-12  | 2017-12-21 | Active    |
+----------+-------+------------------+----------------+-------------+------------+-----------+

感谢您的任何帮助。非常感谢。

0 个答案:

没有答案