关于分组连续日期合并为一起

 
-- 测试数据
create table t(name varchar ( 10 ),date smalldatetime )
insert into t
select ' a ' , ' 2008-01-01 '
union all
select ' a ' , ' 2008-01-02 '
union all
select ' a ' , ' 2008-01-03 '
union all
select ' a ' , ' 2008-01-06 '
union all
select ' a ' , ' 2008-01-07 '
union all
select ' a ' , ' 2008-01-09 '
union all
select ' b ' , ' 2008-01-01 '
union all
select ' b ' , ' 2008-01-02 '
union all
select ' b ' , ' 2008-01-03 '
union all
select ' b ' , ' 2008-01-04 '
union all
select ' b ' , ' 2008-01-07 '
union all
select ' b ' , ' 2008-01-08 '

-- 1要求分组 合并连续的日期 最大和最小
--
2 单独显示不连续的日期

-- 徐王锦 2008/12/30 pm 16:40--

-- 2005
create   function f_4( @name varchar ( 10 )) returns @table table (name varchar ( 10 ),date varchar ( 4000 ))
as
begin
declare @minpx int , @maxpx int , @date smalldatetime , @date2 smalldatetime
declare @table2 table (name varchar ( 10 ),date smalldatetime ,px int )
insert into @table2
 
select name,date,px = row_number() over (partition by name order by date)
  
from t
   
where name = @name
select @minpx = 2 , @maxpx = @@rowcount
select @date = date
 
from @table2
  
where px = 1
insert into @table select @name , convert ( char ( 10 ), @date , 120 )
select @date2 = date
 
from @table2
  
where   px = @minpx
while @minpx <= @maxpx
begin
 
if @date2 = ( select cast ( right (date, 10 ) as smalldatetime ) + 1 from @table where cast ( right (date, 10 ) as smalldatetime ) = @date )
 
begin
  
update a set a.date = a.date + N ' - ' + convert ( char ( 10 ), @date2 , 120 )
   
from @table as a where cast ( right (a.date, 10 ) as smalldatetime ) = @date
 
end
 
else if @date2 > ( select cast ( right (date, 10 ) as smalldatetime ) + 1 from @table where cast ( right (date, 10 ) as smalldatetime ) = @date )
 
begin
  
insert into @table select @name , convert ( char ( 10 ), @date2 , 120 )
 
end
 
select @date = @date2 , @minpx = @minpx + 1
 
select @date2 = date from @table2 where px = @minpx
end
return
end

select
x2.name,
case when len (x2.date) > 10 then left (x2.date, 10 ) + N ' - ' +right (x2.date, 10 ) else x2.date end as date
from
  (
select distinct name from t)x
 
cross apply
  f_4(x.name)
as x2



/*
name       date
---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
a          2008-01-01-2008-01-03
a          2008-01-06-2008-01-07
a          2008-01-09
b          2008-01-01-2008-01-04
b          2008-01-07-2008-01-08

(5 行受影响)

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值