求个日期算法...
当前需求是这样的,要求取出数据库字段'dt'的当前时间前3天,7天,15天,30天,类推...
3天是距当前日期3天内的日期,7天是距当前日期4~7天的日期,15天是距当前日期8~15天的,类推...
请问这个Sql应该如何写,谢谢!
[最优解释]
;with t(id,dt)
as
(
select
number+1 ,
dateadd(dd,number,'2012-11-01')
from
master..spt_values
where
number between 0 and 45
and type='p'
),
m as(
select
dt,
case when dt between getdate() and dateadd(dd,3,getdate()) then '0-3天'
when dt between dateadd(dd,4,getdate()) and dateadd(dd,7,getdate()) then '4-7天'
when dt between dateadd(dd,8,getdate()) and dateadd(dd,15,getdate()) then '8-15天'
when dt between dateadd(dd,16,getdate()) and dateadd(dd,30,getdate()) then '16-30天' end as di
from
t
)
select
*
from
m where di is not null
/*
dt di
----------------------- -------
2012-11-23 00:00:00.000 0-3天
2012-11-24 00:00:00.000 0-3天
2012-11-25 00:00:00.000 0-3天
2012-11-27 00:00:00.000 4-7天
2012-11-28 00:00:00.000 4-7天
2012-11-29 00:00:00.000 4-7天
2012-12-01 00:00:00.000 8-15天
2012-12-02 00:00:00.000 8-15天
2012-12-03 00:00:00.000 8-15天
2012-12-04 00:00:00.000 8-15天
2012-12-05 00:00:00.000 8-15天
2012-12-06 00:00:00.000 8-15天
2012-12-07 00:00:00.000 8-15天
2012-12-09 00:00:00.000 16-30天
2012-12-10 00:00:00.000 16-30天
2012-12-11 00:00:00.000 16-30天
2012-12-12 00:00:00.000 16-30天
2012-12-13 00:00:00.000 16-30天
2012-12-14 00:00:00.000 16-30天
2012-12-15 00:00:00.000 16-30天
2012-12-16 00:00:00.000 16-30天
(21 行受影响)
*/
create table dttest
(
dt datetime
)
insert into dttest values('2012-4-7')
create table temporary
(
beforedt datetime
)
begin
declare @count tinyint
set @count = 0;
while @count<30
begin
insert into temporary
select DATEADD(day,-@count,dt) from dttest
set @count = @count + 1
end
end
select beforedt,case
when beforedt between dateadd(day,-3,dt) and dateadd(day,-1,dt)
then '前1-3天'
when beforedt between dateadd(day,-7,dt) and dateadd(day,-4,dt)
then '前4-7天'
when beforedt between dateadd(day,-15,dt) and dateadd(day,-8,dt)
then '前8-15天'
when beforedt between dateadd(day,-30,dt) and dateadd(day,-16,dt)
then '前16-30天'
end '以前'
from temporary,dttest