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]

示例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.

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

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

示例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

示例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来对该列数据的结果进行排序。

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上按降序对结果进行排序。

示例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.

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

Let’s rerun query using an alias.

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

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

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降序排列。

示例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'

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

示例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 )对结果进行排序。

示例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'

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行。

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函数将完整的结果集划分为指定的组数。

示例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=0Order by BirthDate

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

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

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行。

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行。

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 子句

sql limit 子句_SQL按子句概述和示例相关推荐

  1. sql as关键字_SQL AS关键字概述和示例

    sql as关键字 SQL AS keyword is used to give an alias to table or column names in the queries. In this w ...

  2. sql limit 子句_SQL Join子句介绍和概述

    sql limit 子句 The SQL Join clause is one of the major components of the Select statement, which is us ...

  3. sql limit 子句_SQL有子句–综合指南

    sql limit 子句 Hi, folks. In this article, we will be focusing on SQL Having Clause in detail. 嗨伙计. 在本 ...

  4. sql limit 子句_SQL按子句排序

    sql limit 子句 SQL排序依据 (SQL Order By) SQL Order By clause is used for sorting the result set.SQL Order ...

  5. sql 自定义函数 示例_SQL滞后函数概述和示例

    sql 自定义函数 示例 In the article SQL Server Lead function overview and examples, we explored Lead functio ...

  6. sql update 语句_SQL Update语句概述

    sql update 语句 In this article, we'll walk-through the SQL update statement to modify one or more exi ...

  7. sql字符串函数_SQL字符串函数概述

    sql字符串函数 In this article, we will try to give a brief overview of the SQL string functions used in S ...

  8. sql delete语句_SQL Delete语句概述

    sql delete语句 This article on the SQL Delete is a part of the SQL essential series on key statements, ...

  9. sql stuff 函数_SQL STUFF函数概述

    sql stuff 函数 This article gives an overview of the SQL STUFF function with various examples. 本文通过各种示 ...

最新文章

  1. 标记三维点_细胞器相互作用过程的高速三维全景成像
  2. 自拟计算机作文100字,玩电脑作文100字胡佳慧
  3. 树莓派cpu检测_【树莓派3B+测评】线程的挂起与恢复CPU温度检测
  4. 专访 | 神策数据CEO桑文锋:谁说大数据不需要「小而美」
  5. 在Linux系统里安装Virtual Box的详细步骤 1
  6. mysql数据库 integer_MySQL数据库中,常用的数据类型
  7. OpenSSL制作自签名V3证书
  8. 计算机专业找工作面试面经总结
  9. 移动端H5上传图片裁剪
  10. java代码桥梁收费站_高速公路收费站演讲稿(精简版).doc
  11. puppet一键部署lnmt
  12. ckplayer html5 添加广告,ewebeditor下利用ckplayer增加html5 (mp4)全平台的支持
  13. 【C语言进阶】C语言实现通讯录
  14. 微擎mysql和redis_微擎如何开启redis,redis开启方法详解
  15. JAVA基础编程代码50个
  16. OVS CT连接追踪实现NAT
  17. 【服务器数据恢复】infortrend存储RAID6数据恢复案例
  18. 疫情防控应急广播系统解决方案
  19. php做网站购物车 你搞懂了吗?
  20. 时序预测 | MATLAB实现MA时间序列预测

热门文章

  1. python冒号声明类型_Python 函数参数有冒号 声明后有- 箭头 返回值注释 参数类型注释...
  2. yosemite php gd,Yosemite下配置PHP支持GD库FreeType
  3. AGC 012 B - Splatter Painting
  4. C#-求int数组中连续偶数列的个数
  5. vue生成带签名的apk
  6. WPF ----在UserControl的xaml里绑定依赖属性
  7. ViedoUtil获取视频的缩略图
  8. 《Java虚拟机原理图解》1.3、class文件里的訪问标志、类索引、父类索引、接口索引集合...
  9. Apache HTTP Server Version 安装简要记录
  10. Notes on UNPv1 Ch.5