SQL Server Opposite of SELECT TOP

hfyxw5xn  于 2023-10-15  发布在  其他
关注(0)|答案(5)|浏览(148)

Transact-SQL has a handy SELECT TOP 4 [whatever] FROM.........

I want to make a SELECT query returning the last "n" entries from a table instead of the first ones.

This is the query I would use to return the first four items entered at the table, using SELECT TOP:

sql = "SELECT TOP 4 [news_title], [news_date_added], [news_short_description],
[news_ID] FROM [Web_Xtr_News] WHERE ([news_type] = 2 OR [news_type] = 3) AND
[news_language] = '" + Language + "' ORDER BY [news_ID] ASC"

I need to return the last four.

xmd2e60i

xmd2e60i1#

Change the order of the table from ASC to DESC .

tvz2xvvm

tvz2xvvm2#

It's exactly this: http://www.sqlfiddle.com/#!3/6c813/1

with bottom as(  
  select top 4 *
  from tbl
  order by n desc
)
select * 
from bottom
order by n

Data source:

|  N |
|----|
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
| 10 |

Output:

|  N |
|----|
|  7 |
|  8 |
|  9 |
| 10 |
aamkag61

aamkag613#

Continue to use TOP, and reverse the order:

SELECT TOP 4 [news_title],
             [news_date_added],
             [news_short_description],
             [news_ID]
FROM   [Web_Xtr_News]
WHERE  ([news_type] = 2
         OR [news_type] = 3)
       AND [news_language] = @Language
ORDER  BY [news_ID] DESC

(It was rewritten to use parameters of course. Your original is vulnerable to SQL injection .)

qacovj5a

qacovj5a4#

You can reverse the ordering by using DESC instead of ASC at the end of your query.

ibrsph3r

ibrsph3r5#

A quick way to select batches from a list is to create a unique identifier like a (ROW ID) as (1, 2, 3, etc.) and create a nested query.

Select *
from
(select
   row_number() as id
   ,column1
   ,column2
from
  table1
)as D
where D.id (<>=! between)

相关问题