要传递一个日期型的变量给SQL语句,例如传递一个2008-1-16
得到下面的结果:订单号 到期日期 提货日期 超期天数
a 2008-01-01 2007-12-11 -21
a 2008-01-01 2007-12-21 -11
a 2008-01-01 2008-01-11 10
a 2008-01-01 3create table tb(订单号 varchar(10) , 到期日期 datetime, 提货日期 datetime)
insert into tb values('a', '2008-1-01', '2007-12-11' )
insert into tb values('a', '2008-1-01', '2007-12-21')
insert into tb values('a', '2008-1-01', '2008-1-11' )
insert into tb values('a', '2008-1-01', '2008-1-19' )
insert into tb values('a', '2008-1-01', '2008-1-25' )
insert into tb values('a', '2008-1-01', '2008-2-20' )
goselect 订单号,到期日期,提货日期,
超期天数 = datediff(day, isnull((select top 1 提货日期 from tb where 订单号 = t.订单号 and 提货日期 < t.提货日期 and 提货日期>t.到期日期 order by 提货日期 desc),到期日期),提货日期)
from tb tdrop table tb
得到下面的结果:订单号 到期日期 提货日期 超期天数
a 2008-01-01 2007-12-11 -21
a 2008-01-01 2007-12-21 -11
a 2008-01-01 2008-01-11 10
a 2008-01-01 3create table tb(订单号 varchar(10) , 到期日期 datetime, 提货日期 datetime)
insert into tb values('a', '2008-1-01', '2007-12-11' )
insert into tb values('a', '2008-1-01', '2007-12-21')
insert into tb values('a', '2008-1-01', '2008-1-11' )
insert into tb values('a', '2008-1-01', '2008-1-19' )
insert into tb values('a', '2008-1-01', '2008-1-25' )
insert into tb values('a', '2008-1-01', '2008-2-20' )
goselect 订单号,到期日期,提货日期,
超期天数 = datediff(day, isnull((select top 1 提货日期 from tb where 订单号 = t.订单号 and 提货日期 < t.提货日期 and 提货日期>t.到期日期 order by 提货日期 desc),到期日期),提货日期)
from tb tdrop table tb
insert into tb values('a', '2008-1-01', '2007-12-11' )
insert into tb values('a', '2008-1-01', '2007-12-21')
insert into tb values('a', '2008-1-01', '2008-1-11' )
insert into tb values('a', '2008-1-01', '2008-1-19' )
insert into tb values('a', '2008-1-01', '2008-1-25' )
insert into tb values('a', '2008-1-01', '2008-2-20' )
godeclare @t datetime
set @t='2008-1-16'
select 订单号,到期日期,提货日期,
超期天数 = datediff(day, 到期日期, 提货日期)
from tb t
where 提货日期>=@tdrop table tb
/*
订单号 到期日期 提货日期 超期天数
---------- ----------------------- ----------------------- -----------
a 2008-01-01 00:00:00.000 2008-01-19 00:00:00.000 18
a 2008-01-01 00:00:00.000 2008-01-25 00:00:00.000 24
a 2008-01-01 00:00:00.000 2008-02-20 00:00:00.000 50(3 行受影响)
*/