从一个表检索出满足如下条件的Code列表:
Code Dif YM
111 1 200501
111 0 200506
222 1 200301
333 1 200512
如果当前年月为200508,要求检索出的列表为222
如果当前年月为200505,要求检索出的列表为111,222
如果当前年月为200512,要求检索出的列表为222,333
既如果一个code的最大YM的那一条记录的数据的Dif为1,则检索出。
declare @string varchar(100)
select @string=isnull(@string,) + code +, from table where ym<=当前年月 and dif=1
select @string
declare @tb table
(
Code int,
Dif int,
YM int
)
insert @tb
select 111,1,200501 union
select 111,0,200506 union
select 222,1,200301 union
select 333,1,200512
--查询
declare @YM int
set @YM=200512
select distinct code from @tb t
where (select Dif
from @tb A
where A.code=t.code
and
A.YM=(select max(Ym)
from @tb
where code=A.code
and YM<=@YM)
)=1
--结果
/*
code
-----------
222
333
*/