這是我試過的邏輯,它運行成功。謝謝大家。
create table #temp
(
iden int identity(1,1),
ID int,
[rank] int,
[date] date,
dr_id int,
rownum_id int,
grouprecord int
)
Insert into #temp(id,rank,date)
select 1 , 7 ,'07/08/2015'
union all select 1 , 7 ,'09/08/2015'
union all select 1 , 8 ,'08/16/2015'
union all select 1 , 8 ,'08/17/2015'
union all select 1 , 7 ,'08/19/2015'
union all select 1 , 7 ,'08/15/2015'
union all select 2 , 7 ,'08/01/2015'
union all select 2 , 7 ,'08/02/2015'
union all select 2 , 8 ,'08/16/2015'
union all select 2 , 8 ,'08/17/2015'
union all select 2 , 7 ,'08/26/2015'
union all select 2 , 7 ,'08/28/2015'
update t1
set dr_id = t2.rn
from #temp t1 inner join
(select iden, dense_rank() over(order by id) as rn from #temp) t2
on t1.iden = t2.iden
update t1
set rownum_id = t2.rn
from #temp t1 inner join
(select iden, row_number() over(partition by dr_id order by id) as rn from #temp) t2
on t1.iden = t2.iden
select *,row_number() over(order by iden)rn into #temp1 from
(
select t2.*
from #temp t1 inner join #temp t2
on (t1.dr_id = t2.dr_id or t2.dr_id = (t1.dr_id +1)) and (t1.rank<>t2.rank or t2.dr_id = (t1.dr_id +1))
and t2.iden = t1.iden + 1
)a
declare @id int,@miniden int,@maxiden int,@maxid int
set @id = 1
select @maxid = max(iden) from #temp
while exists(select 1 from #temp1 where rn = @id)
begin
Select @miniden = iden from #temp1
where rn = @id
Select @maxiden = iden from #temp1
where rn = @id+1
update #temp
set grouprecord = @id +1
where iden between @miniden and @maxiden
IF(@maxiden IS NULL)
BEGIN
Update #temp
set grouprecord = @id +1
where iden between @miniden and @maxid
END
set @id = @id + 1
SET @miniden =NULL
SET @maxiden = NULL
end
UPDATE #TEMP
SET GROUPRECORD = 1
WHERE GROUPRECORD IS NULL
select * from #temp
編號背後的邏輯是什麼? – TheGameiswar
它是批次ID的組合,即我試圖在新列的基礎上實現最短日期。在這裏相同的ID 7重複2批次,所以我必須得到每批的最低日期...例如對於第一批o/p將是1 | 7 | 07/08/2015 | 1 1 | 8 | 16/08/2015 | 2 1 | 7 | 15/08/2015 | 3 – user2941762
@ user2941762您能準確描述邏輯嗎?例如,對於ID = 1和等級= 7,爲什麼日期2015年7月8日和2015年8月9日的值等於1,並且19/08/2015和2015年8月15日的日期是相同的ID /等級3的值?我看到這裏沒有logi ... –