首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求教一个时间段的有关问题

2012-02-25 
求教一个时间段的问题,用工作举个例子吧比如说jobstartmonthendmonth1141151231791811想得到job1的经历时

求教一个时间段的问题,
用工作举个例子吧
比如说
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



return @thepty+@maxup-@minup+1
END
[解决办法]
测试过,
select job,stuff( '000000000000 ',st,en-st+1,replicate( '1 ',en-st+1))A into #tab1 from 原表

select job,0+max(substring(A,1,1))+max(substring(A,2,1))+max(substring(A,3,1))+max(substring(A,4,1))
+max(substring(A,5,1))+max(substring(A,6,1))+max(substring(A,7,1))+max(substring(A,8,1))
+max(substring(A,9,1))+max(substring(A,10,1))+max(substring(A,11,1))+max(substring(A,12,1))
from #tab1 group by job

热点排行
Bad Request.