当前位置: 代码迷 >> Sql Server >> 按时间查询前一次的记要
  详细解决方案

按时间查询前一次的记要

热度:51   发布时间:2016-04-24 09:59:19.0
按时间查询前一次的记录
create table t
(  emp_id varchar(10) primary key,
   emp_no varchar(10),
   emp_date datetime
)


insert into t values('00001','123','2014-09-17')
insert into t values('00002','123','2014-09-14')
insert into t values('00003','123','2014-09-01')

请教一个问题,如上,给定一个emp_id,怎么查询到emp_no跟所给的emp_id相同的前两个记录(按emp_date检索), 比如给定'00001',前一条记录是‘00002’,前两条记录是'00003'。
------解决思路----------------------
with temp as(
select ROW_NUMBER()over(order by emp_date desc)orderid,* from t t1 
where exists(select * from t where emp_id='00001' and t1.emp_no=t.emp_no and t.emp_date>t1.emp_date )
)
select emp_id,emp_no,emp_date from temp where orderid=1--前一条
union all
select  emp_id,emp_no,emp_date from temp where orderid=2--前二条
  相关解决方案