简体   繁体   English

根据列值T-SQL重置行号

[英]Resetting row number according to column value T-SQL

I have got the following data with a column indicating the first record within what we'll call an episode, though there is no episode ID. 我有以下数据,其中的一列表示我们将称为情节的第一条记录,尽管没有情节ID。 The ID column indicates and individual person. 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 

And I am trying to get a column indicating row number (starting with 0) grouped by ID ordered by start date, but the row number needs to reset when the First_Record column is not null, basically. 我正在尝试获取一个列,该列指示行号(从0开始),该行号按开始日期排序的ID分组,但是基本上,当First_Record列不为null时,需要重置行号。 Hence the desired output column Depth. 因此,所需的输出列深度。

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

I can't seem to think of any solutions although I found a similar thread , but I'm needing help to translate it into what I'm trying to do. 尽管找到了类似的线程 ,但似乎无法想到任何解决方案,但是我需要帮助将其转换为我要尝试执行的操作。 It has to use the First_Record column, as it has been set from specific conditions. 它必须使用First_Record列,因为它是根据特定条件设置的。 Any help appreciated 任何帮助表示赞赏

If you can have only one episode per person (as in your sample data) you can just use row_number() : 如果每个人只有一集(如样本数据中所示),则可以使用row_number()

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

Otherwise, you can calculate the episode grouping using a cumulative sum and then use that: 否则,您可以使用累积总和来计算剧集分组,然后使用该总和:

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;

Now the depth will start from 0. 现在,深度将从0开始。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM