日期:2014-05-16  浏览次数:20529 次

SQL如何按日期的连续顺序置排序号
例如:
日期                              排序号
2014-03-10                       1
2014-03-11                       2
2014-03-12                       3
2014-04-01                       1
2014-04-02                       2
2014-04-05                       1
2014-04-07                       1
即连续的日期才生成顺序号,如果不连续就重新从1生成,
请问如何写sql语句
------解决方案--------------------
use tempdb
go
if OBJECT_ID('tb') is not null drop table tb
go
create table tb(
col_date datetime
,num int
)
insert into tb
select '2014/3/10',null
union all select '2014/3/11',null
union all select '2014/3/12',null
union all select '2014/4/1',null
union all select '2014/4/2',null
union all select '2014/4/5',null
union all select '2014/4/7',null
go
declare @i int
;with mu as (
select col_date,ROW_NUMBER() over(order by GETDATE()) num2,num
from tb
)
,mu2 as (select t1.col_date,t1.num2,case when DATEDIFF(DAY,t2.col_date,t1.col_date)=1 then 1 else 0 end num3,t1.num
from mu t1
left join mu t2 on t1.num2=t2.num2+1
)

update t1 set @i=case when t1.num3=0 then 1 else @i+1 end
,num=isnull(@i,1)
from mu2 t1
left join mu2 t2 on t1.num2=t2.num2+1

select *
from tb
/*
2014-03-10 00:00:00.000 1
2014-03-11 00:00:00.000 2
2014-03-12 00:00:00.000 3
2014-04-01 00:00:00.000 1
2014-04-02 00:00:00.000 2
2014-04-05 00:00:00.000 1
2014-04-07 00:00:00.000 1
*/