日期:2014-05-17 浏览次数:20836 次
select *
from 表
where DATEDIFF(day,getdate(),你的日期字段) = -1 -- 前1天
select *
from 表
where DATEDIFF(day,getdate(),你的日期字段) = -2 -- 前2天
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]( [日期] datetime, [状态] int)
insert [a]
select'2014/1/1',0 union all
select'2014/1/2',1 union all
select'2014/1/3',1 union all
select'2014/1/4',0 union all
select'2014/1/5',0 union all
select'2014/1/6',1 union all
select'2014/1/7',1 union all
select'2014/1/8',1 union all
select'2014/1/9',1 union all
select'2014/1/10',1
--建立b表
select *,row_number() over(order by [日期]) as rn into b from a where [状态] =1
select convert(varchar(10),a.[日期],120) as [日期] ,a.[状态],
convert(varchar(10),max(b.[日期1]),120) as [前N个工作日]
from a left join
(
select a.[日期],b.[日期]as [日期1] from
(
select a.[日期],max(b.rn) as rn from b a left join b b
on a.rn-1 >b.rn-2--'-1是参数'
group by a.[日期]
)a left join b b on a.rn=b.rn
) b on a.[日期]>b.[日期]
group by a.[日期],a.[状态]
order by a.[日期]