请问如何查询倒数第2、3、4条记录CatId CatName AddedDate
--------------------------------
1 Bird 2008-1-1
(省略数万行)
17878 Sheep 2009-9-13
17879 Pig 2009-9-14
17880 Fish 2009-9-15
17881 Dog 2009-9-15 得到
CatId CatName AddedDate
--------------------------------
17880 Fish 2009-9-15
17879 Pig 2009-9-14
17878 Sheep 2009-9-13
--------------------------------
1 Bird 2008-1-1
(省略数万行)
17878 Sheep 2009-9-13
17879 Pig 2009-9-14
17880 Fish 2009-9-15
17881 Dog 2009-9-15 得到
CatId CatName AddedDate
--------------------------------
17880 Fish 2009-9-15
17879 Pig 2009-9-14
17878 Sheep 2009-9-13
select top m * from tablename where id not in (select top n id from tablename order by id asc/*|desc*/) 2.
select top m * into 临时表(或表变量) from tablename order by columnname -- 将top m笔插入到临时表
set rowcount n --只取n条结果
select * from 表变量 order by columnname desc 3.
select top n * from
(select top m * from tablename order by columnname) a
order by columnname desc
4.如果tablename里没有其他identity列,那么:
先生成一个序列,存储在一临时表中.
select identity(int) id0,* into #temp from tablename 取n到m条的语句为:
select * from #temp where id0 > =n and id0 <= m 如果你在执行select identity(int) id0,* into #temp from tablename这条语句的时候报错,那是因为你的DB中间的select into/bulkcopy属性没有打开要先执行:
exec sp_dboption 你的DB名字,'select into/bulkcopy',true
5.如果表里有identity属性,那么简单:
select * from tablename where identity_col between n and m 6.SQL2005开始.可以使用row_number() over()生成行号
;with cte as
(
select id0=row_number() over(order by id),* from tablename
)
select * from cte where id between n to m
(SELECT TOP 4 CatId,CatName,AddedDate FROM TB ORDER BY CatId DESC)AS T ORDER BY CatId
(
SELECT TOP 3 CatId,CatName,AddedDate FROM
(SELECT TOP 4 CatId,CatName,AddedDate FROM TB ORDER BY CatId DESC)AS T ORDER BY CatId )AS T ORDER BY CatId DESC
(最好不要用if else,因为我这个查询是要放在另一个子查询中,不能转换成字符串的形式连接变量,因为写的太复杂了不好看,如果不写成字符串的形式就可以用if else)
(最好不要用if else,因为我这个查询是要放在另一个子查询中,不能转换成字符串的形式连接变量,因为写的太复杂了不好看,如果不写成字符串的形式就可以用if else)
declare @table table(catid int,catname nvarchar(10),addedate datetime)
insert into @table select 1,'bird','2008-1-1'
union all select 17878,'sheep','2009-9-13'
union all select 17879,'pig','2009-9-14'
union all select 17880,'fish','2009-9-15'
union all select 17881,'dog','2009-9-15'
select top 4 *,DATEDIFF(DD,addedate,GETDATE())时差 into # from @table
order by addedate desc
if exists (select * from # a where exists
(select 1 from # b where a.catname=b.catname group by b.addedate having COUNT(*)>2))
select top 3 * from #
else
select top 3 catid,catname,addedate from # order by addedate
go
drop table #
catid catname addedate
----------- ---------- -----------------------
17878 sheep 2009-09-13 00:00:00.000
17879 pig 2009-09-14 00:00:00.000
17880 fish 2009-09-15 00:00:00.000(3 行受影响)
select top 3 *
from tb
where datediff(day,AddedDate,getdate())>0
order by AddedDate desc