简体   繁体   中英

Select 2nd and 3rd newest row in an SQL table

i'm currently developing a news-site. So here is the problem. I want to select the 2nd and 3rd row in a TOP 3.

SELECT TOP 3 * FROM News ORDER BY Date DESC; 

I want to remove the 1st row and only return the 2nd and 3rd row.

Can anyone help?

Try this:

SELECT TOP 2 FROM
( SELECT TOP 3 * FROM News ORDER BY Date DESC ) xx
ORDER BY Date

SQLFiddle: http://www.sqlfiddle.com/#!3/dbb7e/5

You can also do this generically using window functions:

select n.*
from (SELECT n.*, row_number() over (order by date desc) as seqnum
      FROM News n
     ) n
where n.seqnum >= 2 and n.seqnum <= 3;

I just offer this as a general solution. You can also ensure that you get everything from the second date (in case there are more than two items on that date) by using dense_rank() rather than row_number() .

If you know that no two dates will be the same, you could add

where date not in (select max(date) from News)

Or you could look at rowid if you know that the first item will have rowid=0, for example if you created a temp table with the results of your initial query.

I assume, you somehow know what you Top 3 news are by ordering by date descending. Therfore you should use the LIMIT clause with an OFFSET [For sqlite]

SELECT * FROM News ORDER BY Date DESC LIMIT 2 OFFSET 1;
Select top 2 * from News cross apply (select top 3 from news order by date desc)x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM