日期:2014-05-19  浏览次数:20538 次

求教一个时间段的问题,
用工作举个例子吧
比如说
job                         startmonth                       endmonth                
1                                   1                                         4
1                                   1                                         5
1                                   2                                         3
1                                   7                                         9
1                                   8                                         11

想得到job   1的经历时间
按照例子的话应该是
job                             sum_month
1                                     10
不知道说明白没有,请赐教

------解决方案--------------------
declare @a table(job int, st int, en int)
insert @a select 1, 1 ,4
union all select 1, 1, 5
union all select 1, 2, 3
union all select 1, 7, 9
union all select 1, 8, 11
union all select 1,23,45

declare @b table(a int)

select top 100 identity(int,0,1) id into #tmp from syscolumns


insert @b select b.id from #tmp b,@a a where b.id between st and en and job=1

select distinct * into #g from @b

select identity(int,1,1) id1, * into #x from #g a where not exists(select 1 from #g where a.a=a+1) order by a
select identity(int,1,1) id2, * into #y from #g a where not exists(select 1 from #g where a.a+1=a) order by a
select sum(b.a+1)-sum(a.a) from #x a,#y b where a.id1=b.id2
select * from #y

drop table #tmp,#g,#x,#y
------解决方案--------------------
呵呵...

思路:
把包含关系的干掉,把交叉的提取两头,最好在 sum...
------解决方案--------------------
--改修了一下函数~省去了几个不必要的判断!
alter FUNCTION F_WWW(@job int)
RETURNS int
AS
BEGIN
declare @min int,@max int,@thepty int,@minup int,@maxup int
select @min=0,@max=0,@minup=0,@maxup=0,@thepty=-1

select @min=case when startmonth> @maxup and endmonth> @maxup then startmonth else @minup end,
@max=case when startmonth <@maxup and endmonth <@maxup then @maxup else endmonth end,
@thepty=@thepty+case when startmonth> @maxup and endmonth> @maxup then @maxup-@minup+1 else 0 end,
@minup=@min,@maxup=@max
from tt where job=@job order by startmonth