根据列值T-SQL重置行号

时间:2018-07-11 11:15:58

标签: sql sql-server-2008 tsql

我有以下数据,其中有一列指示我们将称为情节的第一条记录,尽管没有情节ID。 ID列表示个人。

ID  StartDate   EndDate     First_Record
1   2013-11-30  2013-12-08  0
1   2013-12-08  2013-12-14  NULL
1   2013-12-14  2013-12-16  NULL
1   2013-12-16  2013-12-24  NULL
2   2001-02-02  2001-02-02  0
2   2001-02-03  2001-02-05  NULL
2   2010-03-11  2010-03-15  0
2   2010-03-15  2010-03-23  NULL
2   2010-03-24  2010-03-26  NULL 

我正在尝试获取一列,该列指示行号(从0开始),该行号由按开始日期排序的ID分组,但是基本上,当First_Record列不为null时,需要重置行号。因此,需要的输出列深度。

ID  StartDate   EndDate     First_Record    Depth
1   2013-11-30  2013-12-08  0               0
1   2013-12-08  2013-12-14  NULL            1
1   2013-12-14  2013-12-16  NULL            2
1   2013-12-16  2013-12-24  NULL            3
2   2001-02-02  2001-02-02  0               0
2   2001-02-03  2001-02-05  NULL            1
2   2010-03-11  2010-03-15  0               0
2   2010-03-15  2010-03-23  NULL            1
2   2010-03-24  2010-03-26  NULL            2

尽管我找到了类似的thread,但似乎没有想到任何解决方案,但是我需要帮助将其转换为我要尝试的方法。它必须使用First_Record列,因为它是根据特定条件设置的。任何帮助表示赞赏

2 个答案:

答案 0 :(得分:2)

如果每个人只有一集(如样本数据中所示),则可以使用row_number()

select t.*, row_number() over (partition by id order by startDate) - 1 as depth
from t;

否则,您可以使用累积总和来计算剧集分组,然后使用:

select t.*,
       row_number() over (partition by id, grp order by startDate) - 1 as depth
from (select t.*,
             count(first_record) over (partition by id order by startdate) as grp
      from t
     ) t;

答案 1 :(得分:0)

现在深度将从0开始。

SELECT t.*
    ,convert(INT, (
            row_number() OVER (
                PARTITION BY id ORDER BY startDate
                )
            )) - 1 AS Depth
FROM t;