根据两日期字段生成两日期间隔天数字段

表结构数据如下:(sdate预计时间,edate实际时间)
id  sdate        edate
1   2010-01-01   2010-01-03
2   2010-01-02   2010-01-04
3   2010-01-04   2010-01-02
4   2010-01-07   2010-01-03
5   2010-01-08   2010-01-08
6   2010-01-15   2010-01-09
7   2010-01-23   2010-01-20

统计结果如下:(按2天的来进行统计,实际时间和预计时间来进行比较)
准交期       数量
...
提前6天      
1  
提前4天      
1
提前2天      
2
当天         
1
延迟2天      
2

....
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([id] int,[sdate] datetime,[edate] datetime)
insert [TB]
select 1,'2010-01-01','2010-01-03' union all
select 2,'2010-01-02','2010-01-04' union all
select 3,'2010-01-04','2010-01-02' union all
select 4,'2010-01-07','2010-01-03' union all
select 5,'2010-01-08','2010-01-08' union all
select 6,'2010-01-15','2010-01-09' union all
select 7,'2010-01-23','2010-01-20'

select * from [TB]



select id,sdate,edate
from tb
/*
准交期       数量
...
提前6天       1  
提前4天       1
提前2天       2
当天          1
延迟2天       2
*/


select
[准交期]=
case when datediff(dd,edate,sdate) < 0 then '延迟' +convert(varchar(2),datediff(dd,edate,sdate)) +''
    
when datediff(dd,edate,sdate) > 0 then '提前' +convert(varchar(2),datediff(dd,edate,sdate)) +''
    
else '当天' end ,
[数量] = count(*)
from tb
where datediff(dd,edate,sdate)%2 = 0
group by datediff(dd,edate,sdate)

/*
准交期      数量
-------- -----------
延迟-2天    2
当天       1
提前2天     1
提前4天     1
提前6天     1

(5 行受影响)
*/

你可能感兴趣的:(object,测试,table,null,insert,2010)