表:
集装箱号 循环开始时间 循环结束时间
SOC001 2012-01-01 2013-01-01
SOC001 2013-01-02 2014-01-01
SOC001 2014-01-02 (空)
SOC002 2013-03-01 2014-02-01
SOC002 2014-02-02 (空)
SOC003 2014-01-04 (空)
现在查找记录,检索条件 “最近结束循环的记录”。
比如输入1.(代表最新一圈)
查询结果:
SOC001 2013-01-02 2014-01-01
SOC002 2013-03-01 2014-02-01
输入2.(代表最新2圈,不够2圈的,显示1圈的)
SOC001 2012-01-01 2013-01-01
SOC001 2013-01-02 2014-01-01
SOC002 2013-03-01 2014-02-01
------解决方案--------------------
select * from (select *,ROW_NUMBER() over(partition by [集装箱号] order by [循环开始时间] desc) as rn from 表) t
where t.rn=1
------解决方案--------------------
参照@dotnetstudio 增加了结束日期不为NULL,
create table test (id nvarchar(10),srq datetime,erq datetime)
insert into test
select 'SOC001','2012-01-01','2013-01-01' union all
select 'SOC001','2013-01-02','2014-01-01' union all
select 'SOC001','2014-01-02',null union all
select 'SOC002','2013-03-01','2014-02-01' union all
select 'SOC002','2014-02-02',null union all
select 'SOC003','2014-01-04',null
select *
from (
select *,
ROW_NUMBER() over(partition by id order by erq desc) as rn
from test
) t
where t.rn<=2 and t.erq is not null