2012-08-27 132 views
0

从表1使用SQL Server 2000如何获得第二个记录起

table1的

id date time 

001 01/02/2012 02:00 
001 02/02/2012 01:00 
001 07/02/2012 08:00 
002 04/02/2012 01:00 
002 15/02/2012 06:00 
... 

我想有效期限栏

期望输出

起获得第二个记录每个ID订单
id date time 

001 02/02/2012 01:00 
001 07/02/2012 08:00 
002 15/02/2012 06:00 
... 

如何进行查询以获取第二条记录。

需要SQL查询帮助

+0

@marc_s,我编辑我的问题,为了有效期限栏 – JetJack

回答

3

如何像

SELECT yt.* 
FROM your_table yt INNER JOIN 
     (
      SELECT [id], 
        MIN([datetime]) first_datetime 
      FROM your_table 
      GROUP BY [id] 
     ) f ON yt.id = f.id 
      AND yt. [datetime] > f.first_datetime 

假设第一条记录是每个ID最小日期。

0

看着数据看起来不是按时间排序的,所以它会使事情变得复杂一点。 我没有一个SQL Server 2000中尝试了这一点,所以我会试评各行,以便你的想法并纠正任何错误:

标识列

create #tmp (MYNEWID int identity, id int, dt datetime) 
创建一个新的临时表从你的表

insert into #tmp select id, dt from table1 

插入记录让每一个记录,除了第一个ID:

select id, dt 
from #tmp T 
where cast(T.id as varchar)+cast(T.dt as varchar) not in 
    (select top 1 cast(X.id as varchar)+cast(X.dt as varchar) 
    from #tmp X 
    where T.id=X.id 
    order by MYNEWID asc) 

下面的代码将无法正常工作,如果有重复的DT的

0
select t1.* from table1 t1 left join 
(select top 1 * from table1) t2 
on t1.id=t2.id and t1.date=t2.date and t1.time=t2.time 
where t2.id is null and t2.date is null and t2.time is null