日期:2014-05-18 浏览次数:20621 次
---------------------------- -- Author :fredrickhu(小F,向高手学习) -- Date :2011-12-26 14:53:26 -- Version: -- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) -- Apr 22 2011 11:57:00 -- Copyright (c) Microsoft Corporation -- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64) -- ---------------------------- --> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] go create table [tb]([id] int,[timedate] datetime) insert [tb] select 1,'2011-7-11 0:00:00' union all select 2,'2011-6-11 0:00:00' union all select 3,'2011-6-11 0:00:00' union all select 4,'2011-6-11 0:00:00' union all select 5,'2011-9-11 0:00:00' union all select 6,'2011-5-11 0:00:00' --------------开始查询-------------------------- ;with f as ( select px=ROW_NUMBER()over(order by timedate desc,id desc),* from tb ) select id,timedate from f where px=(select px+1 from f where ID=3) ----------------结果---------------------------- /*id timedate ----------- ----------------------- 2 2011-06-11 00:00:00.000 (1 行受影响) */
------解决方案--------------------
http://blog.csdn.net/ACMAIN_CHM/archive/2009/04/20/4095531.aspx
mysql参考上面的这个
------解决方案--------------------
try this,
declare @x int select @x:=ifnull(@x,0)+1 as rownum,id,timedate into #t from tab order by timedate desc,id desc select * from #t where rownum= (select rownum+1 from #t where id=[指定的id]) drop table #t
------解决方案--------------------
create table tb(id int,timedate datetime) insert into tb select 1,'2011-7-11 0:00:00' insert into tb select 2,'2011-6-11 0:00:00' insert into tb select 3,'2011-6-11 0:00:00' insert into tb select 4,'2011-6-11 0:00:00' insert into tb select 5,'2011-9-11 0:00:00' insert into tb select 6,'2011-5-11 0:00:00' go declare @id int set @id=2 select top 1 * from tb a where timedate<(select timedate from tb where id=@id) or id<(select top 1 id from tb where timedate=a.timedate and id<=@id order by id desc) order by timedate desc,id desc /* id timedate ----------- ----------------------- 6 2011-05-11 00:00:00.000 (1 行受影响) */ go drop table tb
------解决方案--------------------
MSSQL2005及以上:
create table tb(id int,timedate datetime) insert into tb select 1,'2011-7-11 0:00:00'; insert into tb select 2,'2011-6-11 0:00:00'; insert into tb select 3,'2011-6-11 0:00:00'; insert into tb select 4,'2011-6-11 0:00:00'; insert into tb select 5,'2011-9-11 0:00:00'; insert into tb select 6,'2011-5-11 0:00:00'; go ;WITH cte_1 AS ( SELECT ROW_NUMBER() OVER (ORDER BY timedate DESC,id DESC) AS rn,id FROM dbo.tb) SELECT * FROM cte_1 AS A WHERE rn=(SELEC