现有一张表如下: 编号 内容 日期
--------------------------------
0001 A 2004-01-01
0002 ... 2004-01-11
0001 ... 2004-03-01
0003 ... 2004-01-12现要查询出,最后日期间隔超过30天的编号,其中日期字段是DATE类型或者字符串都可
比如上表应该查询出 0001
--------------------------------
0001 A 2004-01-01
0002 ... 2004-01-11
0001 ... 2004-03-01
0003 ... 2004-01-12现要查询出,最后日期间隔超过30天的编号,其中日期字段是DATE类型或者字符串都可
比如上表应该查询出 0001
上面乱写的
--select distinct 编号 from table
用游标对此记录集进行处理,如果有人员表可以用人员表打开游标DECLARE cur_Dpt CURSOR
local SCROLL DYNAMIC FOR
SELECT select distinct 编号 from table ORDER BY EmpID
IF CURSOR_STATUS('local','cur_dpt') = 0
GOTO END_PRC
OPEN cur_Dpt
FETCH FIRST FROM cur_Dpt INTO @bianhao
WHILE @@FETCH_STATUS = 0
begin
select top 1 @lasttime= 购买时间 from talbe where 编号=@bianhao order by 购买时间 desc ---取得最后一条时间
select * from talbe where 购买时间 =@lasttime-28
--将你的记录处理
end
CLOSE cur_Dpt
DEALLOCATE cur_Dpt
END_PRC:
DEALLOCATE cur_Dpt
from xTable t1
where exist (
select * from xTable t2 where t2.日期 - t1.日期 > 30
)
(select 编号, max(日期) as f1 from table1
group by 编号) ta
inner join
(select 编号, min(日期) as f1 from
(select top 2 编号,日期 from table1
where 编号 in
(select 编号 from table1 group by 编号 having count(编号)>=2)
order by 日期 desc)
b
group by 编号
) tb
on ta.编号=tb.编号
and datediff(d,tb.f1,ta.f1)>30--ta表为最后消费日期
--tb表为倒数第二个消费日期不知道会不会理解错误。