sql 如何获得符合条件的前一条记录数据
当用户升级后,找他升级前的最后一次订单、和下单时间,如何写SQL
比如下面数据:查询出下面两个记录,即VIP为y前该用户的信息。
A 2011-3 11111d
B 2011-1 22222c
user time dingdan vip
A 2011-1 11111c
A 2011-3 11111d
A 2012-1 11111e y
B 2011-1 22222c
B 2012-1 22222d y
[解决办法]
--try
select * from tb as t
where not exists(select 1 from tb where user=t.user and time>t.time )
and vip !='y'
select * from tb as t
where not exists(select 1 from tb where user=t.user and time>t.time )
and vip !='y'
create table #x(userid varchar(1),riqi datetime,code varchar(3),vip varchar(1))
insert into #x values('a','2011-01-01','11a','')
insert into #x values('a','2011-02-01','11b','')----出来
insert into #x values('a','2011-03-01','11c','y')
insert into #x values('a','2011-04-01','11d','')----出来
insert into #x values('a','2011-05-01','11e','y')
insert into #x values('b','2011-01-01','21a','')----出来
insert into #x values('b','2011-03-01','21b','y')
select c.* from #x c,(
select a.userid,max(a.riqi) riqi from #x a,
(select userid,riqi from #x where vip='y')b
where a.riqi<b.riqi and a.userid=b.userid
group by b.riqi,a.userid
)d
where c.userid=d.userid and c.riqi=d.riqi
--结果:
userid riqi code vip
a2011-02-01 00:00:00.00011b
a2011-04-01 00:00:00.00011d
b2011-01-01 00:00:00.00021a