合并记录:每条记录中除时间不同外,其他部分基本相同,将其合并成同一条记录
rt
示例数据如下:
字段:
A B begintime endtime
a b 2006-02-01 2006-02-28
a b 2006-03-01 2006-03-31
表中的大部分记录如上所示,除begintime ,endtime不同之外其他部分基本相同,begintime,endtime无重复
现想得到如下的合并后的数据,即取A,B字段相同的记录中最小的begintime作为合并后的begintime,最大的endtime作为合并后的endtime;相同部分照搬
A B begintime endtime
a b 2006-02-01 2006-03-31
------解决方案--------------------select A, B, begintime =min(begintime), endtime=max(endtime)
from 表名
group by a,b
------解决方案--------------------select A,B,min(begintime) as begintime,max(endtime) as endtime
from t
group by A,B
------解决方案--------------------select A, B,[begintime]=min(begintime),[endtime]=max(endtime)
from 表名
group by a,b
------解决方案--------------------group by a,b是合并
min最小了,max最大
------解决方案----------------------创建测试环境
create table t(A varchar(10),B varchar(10),begintime datetime,endtime datetime,flag int)
--插入测试数据
insert t(A,B,begintime,endtime)
select 'a ', 'b ', '2006-02-01 ', '2006-02-28 ' union all
select 'a ', 'b ', '2006-03-01 ', '2006-03-31 ' union all
select 'a ', 'b ', '2006-04-02 ', '2006-04-21 '
--求解过程
declare @endtime datetime,@a varchar(10),@b varchar(10),@flag int
set @flag = 0
update t
set @flag = case when @a = a and @b = b and datediff(day,@endtime,begintime) = 1 then @flag else @flag + 1 end
,@endtime = endtime,@a = a,@b = b,flag = @flag
select A,B,min(begintime) as begintime,max(endtime) as endtime
from t
group by A,B,flag
--删除测试环境
drop table t
/*--测试结果
a b 2006-02-01 00:00:00.000 2006-03-31 00:00:00.000
a b 2006-04-02 00:00:00.000 2006-04-21 00:00:00.000
*/
------解决方案--------------------declare @t table(A varchar(4),B varchar(4),begintime datetime,endtime datetime)
insert into @t select 'a ', 'b ', '2006-02-01 ', '2006-02-28 '
insert into @t select 'a ', 'b ', '2006-03-01 ', '2006-03-31 '
select
a.A,a.B,a.begintime,min(b.endtime) as endtime
from
(select t.A,t.B,t.begintime from @t t where not exists(select 1 from @t where endtime=t.begintime-1)) a,
(select t.A,t.B,t.endtime from @t t where not exists(select 1 from @t where begintime=t.endtime+1)) b
where
a.A=b.A and a.B=b.B and a.begintime <=b.endtime
group by
a.A,a.B,a.begintime
/*
A B begintime endtime
---- ---- ----------------------- -----------------------
a b 2006-02-01 00:00:00.000 2006-03-31 00:00:00.000
*/