我获得了以下数据,其中有一列指示我们称之为剧集的第一条记录,但没有剧集 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
我正在尝试获取一列,该列指示按开始日期排序的 ID 分组的行号(从 0 开始),但基本上,当 First_Record 列不为空时,需要重置行号。因此是所需的输出列深度。
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 列,因为它是根据特定条件设置的。任何帮助表示赞赏
最佳答案
如果每人只能观看一集(如示例数据中所示),则只需使用 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;
关于sql - 根据列值重置行号T-SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51284102/