选择表中的Top和Last行(SQL Server)

时间:2022-02-09 23:43:04

I'm using this statement in SQLServer and it works fine:

我在SQLServer中使用此语句,它工作正常:

SELECT TOP 1000 *      
FROM [SomeTable]

It gives me the TOP 1000 records from SomeTable, now which keyword should I use instead of Top if I need the Bottom 1000 records from the table?

它给了我SomeTable的TOP 1000记录,如果我需要表中的Bottom 1000记录,现在应该使用哪个关键字而不是Top?

2 个解决方案

#1


45  

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

要获得底部1000,您将需要按降序排列一列,并仍然排在前1000。

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

如果您关心它与之前的顺序相同,则可以使用公用表表达式:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

#2


6  

You must sort your data according your needs (es. in reverse order) and use select top query

您必须根据需要对数据进行排序(以相反的顺序排序)并使用select top query

#1


45  

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

要获得底部1000,您将需要按降序排列一列,并仍然排在前1000。

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

如果您关心它与之前的顺序相同,则可以使用公用表表达式:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

#2


6  

You must sort your data according your needs (es. in reverse order) and use select top query

您必须根据需要对数据进行排序(以相反的顺序排序)并使用select top query