Tsql 为行的GroupID列指定值

Tsql 为行的GroupID列指定值,tsql,Tsql,下面的代码生成下面屏幕截图中的行。目标是添加一个名为GroupID的新列,该列分配屏幕截图右侧以蓝色显示的值 select * into #data from ( values (157, 84152, 'termination', '7/31/2017'), (157, 3025126, 'effective', '8/1/2017'), (157, 3025126, 'termination', '8/31/2018'), (157, 157, 'ef

下面的代码生成下面屏幕截图中的行。目标是添加一个名为
GroupID
的新列,该列分配屏幕截图右侧以蓝色显示的值

select
*
into #data
from
(
    values
    (157, 84152, 'termination', '7/31/2017'),
    (157, 3025126, 'effective', '8/1/2017'),
    (157, 3025126, 'termination', '8/31/2018'),
    (157, 157, 'effective', '9/1/2018'),
    (1176, 30, 'termination', '5/6/2017'),
    (1176, 1176, 'effective', '5/7/2017'),
    (1176, 1176, 'termination', '11/3/2017'),
    (1176, 30, 'effective', '11/4/2017'),
    (1176, 30, 'termination', '5/6/2018'),
    (1176, 1176, 'effective', '5/7/2018'),
    (1176, 1176, 'termination', '11/9/2018'),
    (1176, 30, 'effective', '11/10/2018'),
    (1176, 30, 'termination', '5/3/2019'),
    (1176, 1176, 'effective', '5/4/2019')
) d (CurrentProducerID, FormerProducerID, DateType, DateValue);

alter table #data alter column DateValue date;

select * from #data;

我尝试过使用
row\u number()
,但没有得到理想的结果。以下是我的尝试和结果:

select
*,
--GroupID = row_number() over(partition by CurrentProducerID order by DateValue)
GroupID = row_number() over(partition by CurrentProducerID, FormerProducerID order by DateValue)
from #data;

一种解决方案可以是:-

;with ccc as (
select *,ROW_NUMBER() over (order by (select 1)) id from #data
),cte as (
select t1.*,t2.id [t2id] from ccc t1
    left outer join ccc t2 on t2.CurrentProducerID=t1.CurrentProducerID 
                          and t2.FormerProducerID=t1.FormerProducerID
                          and (t2.DateType='termination' and t1.DateType='effective')
                          and (t1.id+1)=t2.id
),cte2 as (
select cte.id,ROW_NUMBER() over (Partition by CurrentProducerID order by id) [g] from cte where t2id is null
  )
  select cte.CurrentProducerID , cte.FormerProducerID , cte.DateType , cte.DateValue,isnull(cte2.g,cte3.g) g from cte   
    left join cte2 on cte.id=cte2.id
    left join cte2 cte3 on cte.id+1=cte3.id
结果如下:-

CurrentProducerID FormerProducerID日期类型日期值g
一种解决方案如下所示:-

;with ccc as (
select *,ROW_NUMBER() over (order by (select 1)) id from #data
),cte as (
select t1.*,t2.id [t2id] from ccc t1
    left outer join ccc t2 on t2.CurrentProducerID=t1.CurrentProducerID 
                          and t2.FormerProducerID=t1.FormerProducerID
                          and (t2.DateType='termination' and t1.DateType='effective')
                          and (t1.id+1)=t2.id
),cte2 as (
select cte.id,ROW_NUMBER() over (Partition by CurrentProducerID order by id) [g] from cte where t2id is null
  )
  select cte.CurrentProducerID , cte.FormerProducerID , cte.DateType , cte.DateValue,isnull(cte2.g,cte3.g) g from cte   
    left join cte2 on cte.id=cte2.id
    left join cte2 cte3 on cte.id+1=cte3.id
结果如下:-

CurrentProducerID FormerProducerID日期类型日期值g