sql limit 子句_SQL按子句概述和示例

sql limit 子句

This article will cover the SQL ORDER BY clause including syntax, usage scenarios to sort out results in a Select statement.

本文将介绍SQL ORDER BY子句,包括语法,使用场景,以在Select语句中整理结果。

Once we execute a Select statement in SQL Server, it returns unsorted results. We can define a sequence of a column in the select statement column list. We might need to sort out the result set based on a particular column value, condition etc. We can sort results in ascending or descending order with an ORDER BY clause in Select statement.

一旦在SQL Server中执行Select语句,它将返回未排序的结果。 我们可以在select语句列列表中定义列的序列。 我们可能需要根据特定的列值,条件等对结果集进行排序。我们可以使用Select语句中的ORDER BY子句按升序或降序对结果进行排序。

SQL Order By子句语法 (SQL Order By clause syntax)

We can see the syntax for SQL Order by clause as follows.

我们可以看到SQL Order by子句的语法如下。

SELECT * FROM table_name ORDER BY [column_name] ASC|DESC

In SQL ORDER BY clause, we need to define ascending or descending order in which result needs to be sorted.

在SQL ORDER BY子句中,我们需要定义需要对结果进行排序的升序或降序。

  • ASC: We can specify ASC :我们可以指定ASC to sort the result in ascending order ASC对结果进行升序排序
  • DESC: We can specify DESC :我们可以指定DESC to sort the result in descending order DESC对结果进行降序排序

By default, SQL Server sorts out results using ORDER BY clause in ascending order. Specifying ASC in order by clause is optional.

默认情况下,SQL Server使用ORDER BY子句以升序对结果进行排序。 以order by子句指定ASC是可选的。

Let us explore the SQL ORDER BY clause using examples.

让我们使用示例探索SQL ORDER BY子句。

In this article, I am using AdventureWorks2017 database for all examples. Execute the following query in SSMS. We are not using ORDER BY clause in this query.

在本文中,所有示例均使用AdventureWorks2017数据库。 在SSMS中执行以下查询。 我们不在此查询中使用ORDER BY子句。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]

Sample data without Order by clause

示例1:使用SQL Order By子句对在Select语句中定义的列上的结果进行排序 (Example 1: Sort results on a column defined in a Select statement using SQL Order By clause)

Suppose our requirement is to sort the result by BirthDate column. This column is also specified in the column list of Select statement.

假设我们的要求是按BirthDate列对结果进行排序。 该列也在Select语句的列列表中指定。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
       Order by BirthDate

It uses a default sort method (ascending) because we have not specified any sort order in this query.

它使用默认的排序方法(升序),因为我们没有在此查询中指定任何排序顺序。

Sort data in Ascending order

If we want to sort out results in descending order on birthdate column, we can specify DESC in order by clause.

如果要在生日日期列上按降序排列结果,则可以在order by子句中指定DESC。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
  Order by BirthDate DESC

Sort data in Desending order

示例2:使用SQL Order By子句对未在Select语句中定义的列上的结果进行排序 (Example 2: Sort results on a column not defined in a Select statement using SQL Order By clause)

In the previous example, we sorted out results on the birthdate column. We have specified this column in select statement column list as well.

在前面的示例中,我们在“ 生日”列上整理了结果。 我们也在select语句列列表中指定了该列。

Suppose we want to sort out results on birthday column, but this column is not specified in the select statement. We can still sort results on a column not defined in a Select statement.

假设我们要对生日列的结果进行排序,但是在select语句中未指定此列。 我们仍然可以对未在Select语句中定义的列上的结果进行排序。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
  Order by BirthDate DESC

Sort results on a column not defined in a Select statement using SQL Order By clause

示例3:使用SQL Order By子句按Select语句中的列位置对结果进行排序 (Example 3: Sort results by column positions in a Select statement using SQL Order By clause)

In previous examples, we specified the column name in Order by clause to sort results in ascending or descending order. We can also specify column position in Order by clause.

在前面的示例中,我们在Order by子句中指定了列名,以按升序或降序对结果进行排序。 我们还可以在Order by子句中指定列位置。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
Order by 3 DESC

In this query, column birthdate is at the 3rd position; therefore, we can use three in the Order by clause to sort results on this column data.

在此查询中,birthdate列位于第3个位置; 因此,我们可以在Order by子句中使用3来对该列数据的结果进行排序。

Sort results by column positions in a select statement using SQL Order By clause

Note: I would not recommend using column position in Order By clause. You should always use a column name in Order by clause.

注意: 我不建议在Order By子句中使用列位置。 您应该始终在Order by子句中使用列名。

  • Finding out sort column name might be inconvenient. If we are using a large query, it becomes difficult to identify each column position

    找出排序列名称可能很不方便。 如果我们使用的是大型查询,则很难确定每个列的位置
  • If we make any changes in the column list of Select statement, we need to change the value in order by clause to reflect correct column position no

    如果我们在Select语句的列列表中进行了任何更改,则需要更改order by子句中的值以反映正确的列位置。

示例4:使用SQL Order By子句对Select语句中多个列上的结果进行排序 (Example 4: Sort results on multiple columns in a Select statement using SQL Order By clause)

We can sort results based on multiple columns as well in a select statement. Suppose we want to get results in the following the order.

我们还可以在select语句中基于多个列对结果进行排序。 假设我们要按以下顺序获取结果。

  • Ascending order 升序
  • Descending order 降序

We can specify both ascending and descending order on both columns as shown in the following query.

我们可以在两列中同时指定升序和降序,如以下查询所示。

SELECT [NationalIDNumber]
     ,SickLeaveHours
      ,[Vacationhours]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]
where MaritalStatus='M'
Order by SickLeaveHours ASC , [Vacationhours] desc

In the following screenshot, you can see the result is sorted in ascending order for SickLeaveHours. If there are multiple rows with the same value for SickLeaveHours, it further sorts results on Vacationhours in descending order.

在下面的屏幕截图中,您可以看到结果以SickLeaveHours的升序排列。 如果有多个行的SickLeaveHours值相同,则它将在Vacationhours上按降序对结果进行排序。

Sort results on multiple columns in a select statement using SQL Order By clause

示例5:使用SQL Order By子句对Select语句中别名列上的结果进行排序 (Example 5: Sort results on alias columns in a Select statement using SQL Order By clause)

Many times, we define an alias on a column in a Select statement. Suppose you want to get maximum value in a column using the max function. We can specify a column name to appear in the output. If we do not specify any column name, we get the output without any column name.

很多时候,我们在Select语句的列上定义别名。 假设您要使用max函数在列中获取最大值。 我们可以指定一个列名称以显示在输出中。 如果不指定任何列名,则得到的输出将不包含任何列名。

SELECT Max(SickLeaveHours)
       FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'

In the following screenshot, you can see we get the output without any column name.

在下面的屏幕截图中,您可以看到我们得到的输出没有任何列名。

Column with SQL Alias

Let’s rerun query using an alias.

让我们使用别名重新运行查询。

SELECT Max(SickLeaveHours) as MAXSickHours
       FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'

Column with Alias

We can use the Order by clause for an alias column as well. Suppose we want to define an alias on SickLeaveHours as [SickHours]. Further, we want to use this alias in Order by clause to sort results in descending order.

我们也可以将Order by子句用于别名列。 假设我们要在SickLeaveHours上将别名定义为[SickHours]。 此外,我们想在Order by子句中使用此别名对结果进行降序排序。

SELECT [NationalIDNumber]
  , SickLeaveHours as [SickHours]  --Alias Column
      ,[Vacationhours]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'
Order by [SickHours] DESC --Sort by Alias

In the following screenshot, We can see alias column SickHours sorted in descending order.

在以下屏幕截图中,我们可以看到别名列SickHours降序排列。

Sort results on alias columns in a select statement using SQL Order By clause

示例6:使用SQL Order By子句在Select语句中对带有表达式的结果进行排序 (Example 6: Sort results with expression in a Select statement using SQL Order By clause)

We can use expressions as well in Order by clause. Suppose we want to sort for a year in a date column. Let us run the query without any Order by clause first.

我们也可以在Order by子句中使用表达式。 假设我们要在日期列中排序一年。 让我们先运行不带任何Order by子句的查询。

SELECT top 10 [NationalIDNumber]
  , SickLeaveHours as [SickHours]
      ,[Vacationhours]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'

Query without Order by clause

Now, we want to sort on Birthdate column yearly in ascending order. I am using the TOP clause to limit result in the output. We are using DATEPART function we get a specified part of a date. In this query, we want to extract year to sort data using the DATEPART function.

现在,我们想按升序在“ 生日”列上进行排序。 我正在使用TOP子句来限制输出结果。 我们正在使用DATEPART函数获得日期的指定部分。 在此查询中,我们要提取年份以使用DATEPART函数对数据进行排序。

SELECT top 10 [NationalIDNumber]
  , SickLeaveHours as [SickHours]
      ,[Vacationhours]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'
Order by DATEPART(YEAR , BirthDate) ASC

Sort results with expression in a select statement using SQL Order By clause

示例6:使用SQL Order By子句使用归类对结果进行排序 (Example 6: Sort results with Collation using SQL Order By clause)

Suppose we have a table that contains column having case sensitive data. We might want to sort results specifying the collation in Order by clause.

假设我们有一个表,其中包含具有区分大小写的数据的列。 我们可能想对在Order by子句中指定排序规则的结果进行排序。

Let us create a table with Latin1_General_CI_AI collation and later we will sort it using another collation Latin1_General_CS_AS.

让我们用Latin1_General_CI_AI排序规则创建一个表,然后再使用另一个排序规则Latin1_General_CS_AS对其进行排序。

You can find the definition of both collations in the following table.

您可以在下表中找到这两种归类的定义。

Latin1_General_CI_AI

Latin1-General, case-insensitive, accent-insensitive, kanatype-insensitive, width-insensitive

Latin1_General_CS_AS

Latin1-General, case-sensitive, accent-sensitive, kanatype-insensitive, width-insensitive

拉丁语1_General_CI_AI

Latin1常规,不区分大小写,不区分重音,不区分假名类型,不区分宽度

Latin1_General_CS_AS

Latin1常规,区分大小写,区分重音,不区分假名类型,不区分宽度

Use SQLShackDemo
Go
CREATE TABLE #temp1 (EmpName nvarchar(20) COLLATE Latin1_General_CI_AI)  
GO  
INSERT INTO #temp1 VALUES(N'Rajendra'),(N'raJendra'),(N'rajendraA'),(N'rAjEnDrA'),(N'rajendra'),(N'RAJENDRA');

Let us sort out results without specifying any sort condition. It uses the collation defined in the EmpName column (Latin1_General_CI_AI).

让我们对结果进行排序,而不指定任何排序条件。 它使用在EmpName列(Latin1_General_CI_AI)中定义的排序规则。

Query 1:

查询1:

SELECT EmpName  
FROM #temp1  
ORDER BY EmpName;

Query 2:

查询2:

SELECT EmpName  
FROM #temp1   
ORDER BY EmpName COLLATE Latin1_General_CS_AS

In the following output, you can see a difference in the result of both queries. In the Query1, it uses default column collation (Latin1_General_CI_AI) for sorting results. In Query2, it uses collation (Latin1_General_CS_AS) specified in Order by clause to sort results.

在以下输出中,您可以看到两个查询的结果有所不同。 在Query1中,它使用默认的列排序规则Latin1_General_CI_AI )对结果进行排序。 在Query2中,它使用Order by子句中指定的排序规则Latin1_General_CS_AS )对结果进行排序。

Sort results with collation using SQL Order By clause

示例7:使用SQL Order By子句使用Rank函数对结果进行排序 (Example 7: Sort results using a Rank function using SQL Order By clause )

We can use built-in Ranking functions in SQL Server with Order by clause as well. We can use Rank functions to provide a rank in a set of rows. We have following Rank functions in SQL Server.

我们也可以在SQL Server中通过Order by子句使用内置的Ranking函数。 我们可以使用Rank函数在一组行中提供一个排名。 我们在SQL Server中具有以下Rank函数。

  1. ROW_NUMBER

    ROW_NUMBER
  2. RANK

  3. DENSE_RANK

    DENSE_RANK
  4. NTILE

    尼蒂尔

Let us explore the use of Order By clause with each Ranking functions.

让我们探讨在每个排名函数中使用Order By子句的情况。

ROW_NUMBER

ROW_NUMBER

We can use ROW_NUMBER to provide row number in a specified column based on Order By clause.

我们可以使用ROW_NUMBER在基于Order By子句的指定列中提供行号。

In the following query, we want to get row number for SickLeaveHours column values in ascending order.

在下面的查询中,我们要以升序获取SickLeaveHours列值的行号。

SELECT [NationalIDNumber]
   ,SickLeaveHours 
   ,ROW_NUMBER() OVER (ORDER BY [SickLeaveHours] ASC ) AS "Row_Number"  
 FROM [AdventureWorks2017].[HumanResources].[Employee]
Where MaritalStatus='M'

Sort results using a Rank function using SQL Order By clause

RANK: In Rank function, we get a rank for each row based on column value specified. If there are multiple rows with a similar value, it gives the same rank but skips the next number in the sequence.

排名在Rank函数中,我们根据指定的列值获得每一行的排名。 如果有多个具有相似值的行,它将给出相同的等级,但会跳过序列中的下一个数字。

In the following query, we specified Row_Number() and RANK() function along with Order by clause for SickLeaveHours column.

在以下查询中,我们为SickLeaveHours列指定了Row_Number()RANK()函数以及Order by子句。

SELECT  [NationalIDNumber]
     , SickLeaveHours 
       ,ROW_NUMBER() OVER (ORDER BY [SickLeaveHours] ASC ) AS "Row_Number" 
        ,RANK() OVER (ORDER BY SickLeaveHours) AS "Rank"
           FROM [AdventureWorks2017].[HumanResources].[Employee]
     where MaritalStatus='M'

In the following screenshot, we can see for result sorted out using SickLeaveHours. In the Rank function, it skips value 2-3 because we have 3 rows for SickLeaveHours 20.

在以下屏幕截图中,我们可以看到使用SickLeaveHours整理出的结果。 在Rank函数中,它跳过值2-3,因为SickLeaveHours 20有3行。

Sort results using a Rank function using SQL Order By clause

Similarly, we can use DENSE_RANK() and NTILE(4) with Order by clause in a select statement.

同样,我们可以在select语句中将DENSE_RANK()NTILE(4)与Order by子句一起使用。

SELECT  [NationalIDNumber]
     , SickLeaveHours 
       ,ROW_NUMBER() OVER (ORDER BY [SickLeaveHours] ASC ) AS "Row Number" 
     ,RANK() OVER (ORDER BY SickLeaveHours) AS "Rank"
     ,DENSE_RANK() OVER (ORDER BY SickLeaveHours) AS "DENSE_Rank",
     NTILE(4) OVER (ORDER BY SickLeaveHours) AS [NTILE]
           FROM [AdventureWorks2017].[HumanResources].[Employee]
     where MaritalStatus='M'

In the output, we can see DENSE_RANK() gives a rank for each row based on the conditions specified in Order by clause. It does not skip the next value in rank if we have multiple rows with similar values.

在输出中,我们可以看到DENSE_RANK()根据Order by子句中指定的条件为每一行给出了一个等级。 如果我们有多个具有相似值的行,它不会跳过排名中的下一个值。

The NTILE function divides the complete result sets into the number of groups specified.

NTILE函数将完整的结果集划分为指定的组数。

Sort results using a Rank function using SQL Order By clause

示例8:使用SQL Order By子句限制行数 (Example 8: Limit number of rows using SQL Order By clause )

We can skip some rows with OFFSET and FETCH in an Order by clause. First, let us run the following query and view the output in SSMS.

我们可以在Order by子句中使用OFFSET和FETCH跳过一些行。 首先,让我们运行以下查询并查看SSMS中的输出。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
 where Salariedflag=0
 Order by BirthDate

In the following screenshot, we can see this query returns 238 rows.

在以下屏幕截图中,我们可以看到此查询返回238行。

Sort results using a Rank function using SQL Order By clause

Suppose we want to Skip the first 100 rows from the sorted result set and return all remaining rows. We can use OFFSET with Order by clause.

假设我们要跳过排序结果集中的前100行,并返回所有剩余的行。 我们可以将OFFSET与Order by子句一起使用。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
where Salariedflag=0
Order by BirthDate OFFSET 100 ROWS;

In the output, we get 138 rows because it skips first 100 rows from the sorted result.

在输出中,我们得到138行,因为它从排序结果中跳过了前100行。

Order by clause with OFFSET

Suppose we want to skip 100 rows from the sorted result. We further need only first 20 rows from the result set. We can specify the following values along with Order by clause.

假设我们要从排序结果中跳过100行。 我们进一步只需要结果集中的前20行。 我们可以指定以下值以及Order by子句。

  • OFFSET value of 100

    偏移值为100
  • FETCH NEXT value 20

    FETCH NEXT值20

Execute the following query and view the output.

执行以下查询并查看输出。

SELECT [NationalIDNumber]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[ModifiedDate]
      ,[SalariedFlag]
       FROM [AdventureWorks2017].[HumanResources].[Employee]
Where Salariedflag=0
Order by BirthDate
OFFSET 100 ROWS FETCH NEXT 20 ROWS ONLY;

In the output, we can see that only the first 20 rows after skipping 100 records in sorted result.

在输出中,我们可以看到跳过排序结果中的100条记录后仅前20行。

Order by clause with OFFSET and Fetch Next Rows

Note: We can use OFFSET and FETCH in SQL Order By clause starting from SQL Server 2012.

注意 :从SQL Server 2012开始,我们可以在SQL Order By子句中使用OFFSET和FETCH。

翻译自: https://www.sqlshack.com/sql-order-by-clause-overview-and-examples/

sql limit 子句

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值