日期:2014-05-17  浏览次数:20704 次

去除周末算间隔天数的问题。

With dt1 as(
Select 0 as id, '2013-01-01' as c1,'2013-01-04' as c2 union all 
Select 1,'2013-01-02','2013-01-03' union all 
Select 2,'2013-01-03','2013-01-07' union all 
Select 3,'2013-01-04','2013-01-06' union all 
Select 4,'2013-01-05','2013-01-08' union all 
Select 5,'2013-01-06','2013-01-11' union all 
Select 6,'2013-01-07','2013-01-14' union all 
Select 7,'2013-01-08','2013-01-12' union all 
Select 8,'2013-01-09','2013-01-10' union all 
Select 9,'2013-01-10','2013-01-11' union all 
Select 10,'2013-01-11','2013-01-13' union all 
Select 11,'2013-01-12','2013-01-15' union all 
Select 12,'2013-01-13','2013-01-16' union all 
Select 13,'2013-01-14','2013-01-15' union all 
Select 14,'2013-01-15','2013-01-18' union all 
Select 15,'2013-01-16','2013-01-16' union all 
Select 16,'2013-01-17','2013-01-20'  
),
dt2 as ( Select '2013-01-10' as c1 )
Select id, DATEDIFF(DD,c1,c2) '间隔',c1,c2,
case DATEPART(weekday, c1 ) when 1 then '日' 
when 2 then '一' when 3 then '二' 
when 4 then '三' when 5 then '四' 
when 6 then '五' when 7 then '六' end as 'C1_week',
case DATEPART(weekday, c2 ) when 1 then '日' 
when 2 then '一' when 3 then '二' 
when 4 then '三' when 5 then '四' 
when 6 then '五' when 7 then '六' end as 'C2_week' from dt



数据表为dt1;
算出c1与c2之间的间隔,要求如下:

1:当 c1 与 c2 在同一周的星期一到星期五之间,间隔几天就是几天 
如:2013-01-01 周二  2013-01-04 周五 间隔3天

2:当 c1 、c2 在星期一到星期五之间但不在同一周,间隔天数要减去 周六 周日
如:2013-01-03 周四  2013-01-07 周一 间隔2天

3:当 c1在星期一到五之间,c2 在周六 周日。去除周末,但不去除本身
算法如下:
2013-01-04 周五 2013-01-05 周六 间隔1天 
2013-01-04 周五 2013-01-06 周日 间隔1天 去除了 周六
2013-01-04 周五 2013-01-13 周日 间隔6天 去除了 5,6号周六、周日 和 12号的周六

4:当 c2在星期一到五之间,c1 在周六 周日。去除周末,但不去除本身
算法和3一样,只是c1和c2对换位置。

5:c1 c2同一天 间隔为0;

6: c1 c2都在周末,去除非本身的周末日期。