要传递一个日期型的变量给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
-----你的到期天数写的太复杂了
select 订单号,到期日期,提货日期,
超期天数 = datediff(day, 提货日期,到期日期)
from tb t
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' )
go
这个是想要的结果
订单号 到期日期 提货日期 超期天数
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 3
declare @date datetime
set @date = '2008-1-16'select 订单号,到期日期,提货日期,
超期天数 =
datediff(day,提货日期,@date)
from #tb t
declare @tb table (订单号 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' )set @传入日期='2008-01-16' -----传入参数
select 订单号,
到期日期=convert(varchar(10),到期日期,120),
提货日期=case when 提货日期>@传入日期 then '' else convert(char(10),提货日期,120) end,
超期天数=case when 提货日期<@传入日期 then datediff(day,到期日期,提货日期) else datediff(day,@传入日期,提货日期) end
from @tb t
where 提货日期<=(select min(提货日期) from @tb where 提货日期>@传入日期)
/*
订单号 到期日期 提货日期 超期天数
-------------------------------------------------------
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 3*/