我有一张有 400 行的表。我想选择最后 6 行,不包括最后一行。
使用以下代码,我得到最后 6 行,但我不希望最后(第 400 行)存在
SELECT *
FROM ImagesInfo
WHERE Image_Id IN
( SELECT TOP 6 Image_Id
FROM ImagesInfo
ORDER BY Image_Id DESC )
我有一张有 400 行的表。我想选择最后 6 行,不包括最后一行。
使用以下代码,我得到最后 6 行,但我不希望最后(第 400 行)存在
SELECT *
FROM ImagesInfo
WHERE Image_Id IN
( SELECT TOP 6 Image_Id
FROM ImagesInfo
ORDER BY Image_Id DESC )
使用ROW_NUMBER()
语法
SELECT *
from
(
SELECT *, ROW_NUMBER() over (ORDER By Image_ID) rn
FROM yourtable
) v
WHERE rn between x and y
SELECT top 6 *
FROM
( SELECT TOP 7 *
FROM ImagesInfo
ORDER BY Image_Id DESC
) t
ORDER BY Image_Id
看看偏移量
SELECT First Name + ' ' + Last Name FROM Employees ORDER BY First Name OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;
[微软 SQL Server 网站]
select top 6 * from image_info
where image_id not in(select max(image_id) from image_info)
order by image_id desc
关于什么:
SELECT * FROM ImagesInfo
WHERE Image_Id IN (SELECT TOP 6 Image_Id FROM ImagesInfo ORDER BY Image_Id DESC) AND
Image_Id <> (SELECT TOP 1 Image_Id FROM ImagesInfo ORDER BY Image_Id DESC)
或者
SELECT * FROM ImagesInfo
WHERE Image_Id IN (SELECT TOP 6 Image_Id FROM ImagesInfo ORDER BY Image_Id DESC) AND
Image_Id <> (SELECT MAX(Image_Id) FROM ImagesInfo)
如果我理解正确(我不确定)那么你应该能够做到:
SELECT *
FROM ImagesInfo
WHERE Image_Id IN
( SELECT TOP 7 Image_Id
FROM ImagesInfo
ORDER BY Image_Id DESC )
and Image_Id not IN
( SELECT TOP 1 Image_ID
FROM ImagesInfo
ORDER BY Image_Id DESC )
尝试这个:
您只需从结果集中消除最大记录
SELECT *
FROM ImagesInfo
WHERE Image_Id IN
( SELECT TOP 6 Image_Id
FROM ImagesInfo
where Image_Id<> (select MAX(Image_Id) from ImagesInfo )
ORDER BY Image_Id DESC )
或者
如果您使用的是sql server 2005 或更高版本:您可以使用ROW_NUMBER()和 CTE
with cte as(
SELECT *,
ROW_NUMBER() over (order by Image_Id desc) as row_num
FROM ImagesInfo)
select * from cte where row_num between 2 and 7