sql示例

This article explores the SQL Server Lead function and its usage with various examples.

本文通过各种示例探讨了SQL Server Lead函数及其用法。

介绍 (Introduction)

We need to perform statistical and Computational operations on the data. SQL Server provides many analytical and window functions to do the task without any complexity. We can write complex queries using these window functions.

我们需要对数据执行统计和计算操作。 SQL Server提供了许多分析和窗口函数来完成任务而没有任何复杂性。 我们可以使用这些窗口函数编写复杂的查询。

We have following Window functions in SQL Server.

在SQL Server中,我们具有以下Window函数。

  • Ranking function – RANK, DENSE_RANK, ROW_Number and NTILE 排名函数– RANK,DENSE_RANK,ROW_Number和NTILE
  • Aggregate function – SUM, MIN, MAX, AVG and Count 汇总功能– SUM,MIN,MAX,AVG和计数
  • Value functions – LEAD, LAG, FIRST_VALUE and LAST_VALUE 值函数– LEAD,LAG,FIRST_VALUE和LAST_VALUE

Let’s look at the SQL Server Lead function in the next section of this article.

让我们在本文的下一部分中查看SQL Server Lead函数。

SQL Server Lead功能 (SQL Server Lead function)

The lead function is available from SQL Server 2012. This function is part of a Window function. Suppose we need to compare an individual row data with the subsequent row data, Lead function in SQL Server helps SQL developers in this regard.

Lead函数可从SQL Server 2012获得。此函数是Window函数的一部分。 假设我们需要将单个行数据与后续行数据进行比较,SQL Server中的Lead函数在这方面可以帮助SQL开发人员。

Let’s prepare the sample data using the following query. In the following table, we use a table variable to define the columns, data types and insert data into that.

让我们使用以下查询准备示例数据。 在下表中,我们使用表变量定义列,数据类型并将数据插入其中。

DECLARE   @Employee TABLE(EmpCode VARCHAR(10),EmpName   VARCHAR(10),JoiningDate  DATE)
INSERT INTO @Employee VALUES ('1', 'Rajendra', '1-Sep-2018')
INSERT INTO @Employee VALUES ('2', 'Manoj', '1-Oct-2018')
INSERT INTO @Employee VALUES ('3', 'Sonu', '10-Mar-2018')
INSERT INTO @Employee VALUES ('4', 'Kashish', '25-Oct-2018')
INSERT INTO @Employee VALUES ('5', 'Tim', '1-Dec-2018')
INSERT INTO @Employee VALUES ('6', 'Akshita', '1-Nov-2018')SELECT * FROM   @Employee;

Let’s look at the syntax and arguments for this function.

让我们看一下该函数的语法和参数。

Lead函数的语法
(Syntax of Lead function
)

LEAD(scalar_expression ,offset [,default])
OVER (
      [PARTITION BY partition_expression, … ]
      ORDER BY sort_expression [ASC | DESC], …

LEAD(scalar_expression,offset [,default])
OVER(
[PARTITION BY partition_expression,...]
ORDER BY sort_expression [ASC | DESC],…

  • Scalar_expression: It contains the column name or expression for which we want to apply the lead function Scalar_expression:包含我们要对其应用前导函数的列名或表达式
  • Offset: It is the number of rows ahead from the current row. The lead function uses this argument to fetch the value. We can use an expression, subquery or a positive integer value in this argument. It is an optional argument. If we do not specify any value, SQL Server considers the default value as positive integer value 1 偏移量:它是当前行之前的行数。 Lead函数使用此参数来获取值。 我们可以在此参数中使用表达式,子查询或正整数值。 它是一个可选参数。 如果未指定任何值,则SQL Server会将默认值视为正整数值1
  • Default: We can specify a default value for this argument. If the SQL Server Lead function crosses the boundary of a partition of no values are available, it shows the default value in the output. It is also an optional parameter and returns NULL if no values are specified 默认值:我们可以为此参数指定默认值。 如果SQL Server Lead函数越过没有可用值的分区的边界,它将在输出中显示默认值。 它也是一个可选参数,如果未指定任何值,则返回NULL
  • PARTITION BY: We can create data set partitions using PARTITION BY argument. It is also an optional argument. If we do not specify this argument, SQL Server considers complete data set a single partition PARTITION BY:我们可以使用PARTITION BY参数创建数据集分区。 这也是一个可选参数。 如果不指定此参数,则SQL Server会将完整的数据集视为一个分区
  • ORDER BY: Order by clause sorts the data in ascending or descending order. If we use partitions ( by PARTITION BY clause), it sorts the data in each partition ORDER BY:Order by子句对数据进行升序或降序排序。 如果我们使用分区(通过PARTITION BY子句),它将对每个分区中的数据进行排序

Let’s understand the SQL Server Lead function using examples.

让我们使用示例来了解SQL Server Lead函数。

示例1:无默认值的引导函数 (Example 1: Lead function without a default value)

In this example, execute the following query in the same window in which we declared the table variable and data. For simplicity, I do not specify the variable table declaration again and again.

在此示例中,在我们声明表变量和数据的同一窗口中执行以下查询。 为了简单起见,我没有一次又一次地指定变量表声明。

SELECT *, LEAD(JoiningDate, 1) OVER(ORDER BY JoiningDate ASC) AS EndDate
FROM @Employee;

In this output, we can see that the Lead function gets the value of the subsequent row and return NULL if no subsequent row is available and the default value is also not specified.

在此输出中,我们可以看到Lead函数获取下一行的值,如果没有下一行可用并且也未指定默认值,则返回NULL。

示例2:具有默认值的引导函数 (Example 2: Lead function with a default value)

Let’s specify a default value for the argument default and rerun the query.

让我们为参数default指定一个默认值,然后重新运行查询。

SELECT *, LEAD(JoiningDate, 1,0) OVER(ORDER BY JoiningDate ASC) AS EndDate
FROM @Employee;

We get an error message – Operand type clash: int is incompatible with date

我们收到一条错误消息– 操作数类型冲突:int与日期不兼容

In the table variable, we have the JoiningDate column defined as Date. We also applied the SQL Server Lead function on the date data type. We cannot use an integer data type value for the date data type. Due to this, we get this error message of the incompatible data type.

在表变量中,我们将JoiningDate列定义为Date。 我们还对日期数据类型应用了SQL Server Lead函数。 我们不能使用整数数据类型值作为日期数据类型。 因此,我们收到了不兼容数据类型的错误消息。

Let’s specify the default date in this argument and rerun the query.

让我们在此参数中指定默认日期,然后重新运行查询。

SELECT *, LEAD(JoiningDate, 1,'2018-01-01') OVER(ORDER BY JoiningDate ASC) AS EndDate
FROM @Employee;

In this output, we get the specified default date instead of the NULL value.

在此输出中,我们获得指定的默认日期而不是NULL值。

示例3:带有PARTITION BY子句SQL Server Lead函数 (Example 3: SQL Server Lead function with PARTITION BY clause)

To explain the use of the PARTITION BY clause along with the lead function, let’s create another table and insert data into it.

为了说明PARTITION BY子句与Lead函数一起使用的方法,让我们创建另一个表并将数据插入其中。

CREATE TABLE dbo.ProductSales
([Year]  INT,[Quarter] TINYINT,Sales     DECIMAL(9,2)
);INSERT INTO dbo.ProductSales VALUES (2017, 1, 55000.00)
,(2017, 2, 78000.00)
,(2017, 3, 49000.00)
,(2017, 4, 32000.00)
,(2018, 1, 41000.00)
,(2018, 2,  8965.00)
,(2018, 3, 69874.00)
,(2018, 4,  32562.00)
,(2019, 1, 87456.00)
,(2019, 2, 75000.00)
,(2019, 3, 96500.00)
,(2019, 4, 85236.00)

We have following sample data in ProductSales table.

我们在ProductSales表中有以下示例数据。

Let’s run the SQL Server Lead function and view the output.

让我们运行SQL Server Lead函数并查看输出。

SELECT [Year], [Quarter], Sales, LEAD(Sales, 1, 0) OVER(ORDER BY [Year], [Quarter] ASC) AS [NextQuarterSales]
FROM dbo.ProductSales;

We have use partitions in this query, and Lead function treat completes data as a single partition and returns the next quarter sales value.

我们在此查询中使用了分区,并且Lead函数将完整数据视为单个分区,并返回下一个季度的销售值。

Suppose we want to analyze data for a yearly basis. We can partition the data on the Year column using the PARTITION BY clause.

假设我们要每年分析一次数据。 我们可以使用PARTITION BY子句在Year列上对数据进行分区。

SELECT [Year], [Quarter], Sales, LEAD(Sales, 1, 0) OVER(PARTITION BY [Year]ORDER BY [Year], [Quarter] ASC) AS [NextQuarterSales]
FROM dbo.ProductSales;

Let’s look at the output. In this, we can see three partitions for Year 2017,2018 and 2019. SQL Server Lead function takes subsequent value within a year partition and returns the default value for each partition. For example, in the year 2017, we get the default value for quarter 4, and it does not look for the year 2018 quarter 1.

让我们看一下输出。 在这里,我们可以看到三个分区,分别是Year 2017、2018和2019。SQLServer Lead函数在Year分区中获取后续值,并为每个分区返回默认值。 例如,在2017年,我们获得了第4季度的默认值,而没有查找2018年第1季度的默认值。

In the previous query, we use the ORDER BY clause to sort data in ascending order. Let’s sort the data in descending order using the following query.

在上一个查询中,我们使用ORDER BY子句对数据进行升序排序。 让我们使用以下查询按降序对数据进行排序。

SELECT [Year], [Quarter], Sales, LEAD(Sales, 1, 0) OVER(PARTITION BY [Year]ORDER BY [Year], [Quarter] DESC) AS [NextQuarterSales]
FROM dbo.ProductSales;

示例4:SQL Server Lead函数和公用表表达式(CTE) (Example 4: SQL Server Lead function and Common Table Expressions ( CTE) )

We can use the lead function in combination with the CTE for writing complex queries. In the following query, we do the following tasks.

我们可以结合使用Lead函数和CTE来编写复杂的查询。 在以下查询中,我们执行以下任务。

  • Define a CTE 定义CTE
  • Apply Lead function on the CTE to get the required values 在CTE上应用Lead函数以获取所需的值
WITH cte_netsales_2018AS (SELECT [Quarter], SUM(Sales) net_salesFROM dbo.ProductSalesWHERE year = 2018GROUP BY [Quarter])SELECT [Quarter], net_sales, LEAD(net_sales, 1, 0) OVER(ORDER BY [Quarter]) salesFROM cte_netsales_2018;

示例5:SQL Server Lead函数并指定OFFSET参数值 (Example 5: SQL Server Lead function and specify OFFSET argument value)

In the previous examples, we used default offset value 1 to return the subsequent values. Let’s specify the offset value other than the default value and view the output.

在前面的示例中,我们使用默认偏移值1返回后续值。 让我们指定默认值以外的偏移值并查看输出。

SELECT [Year], [Quarter], Sales, LEAD(Sales, 2, 0) OVER(ORDER BY [Year], [Quarter] ASC) AS [NextQuarterSales]
FROM dbo.ProductSales;

For the offset value 2, it skips the next row and gets the value for the current row + 2nd row. Similarly, we can specify the offset value to get the data as per our requirement.

对于偏移值2,它将跳过下一行,并获取当前行+第二行的值。 同样,我们可以根据需要指定偏移值以获取数据。

示例6:带有表达式SQL Server Lead函数 (Example 6: SQL Server Lead function with expressions)

We can use expressions as well in the lead function. In the following query, we specified the following expressions.

我们也可以在Lead函数中使用表达式。 在以下查询中,我们指定了以下表达式。

  • Scalar_expression: To double the sales figure using the 2*sales Scalar_expression:使用2 * sales将销售额增加一倍
  • Offset: we use the expression to calculate the offset value as well 偏移量:我们也使用表达式来计算偏移量值
1+(select min(quarter) from productsales),
SELECT [Year], [Quarter], Sales, LEAD(2*sales, 1+(select min(quarter) from productsales), 0) OVER(ORDER BY [Year], [Quarter] ASC) AS [NextQuarterSales]
FROM dbo.ProductSales;

结论 (Conclusion)

In this article, we explored the useful Window function SQL Server Lead along with various examples. Below is the quick summary of what we learned about SQL Server Lead function in this article:

在本文中,我们探讨了有用的Window函数SQL Server Lead以及各种示例。 以下是我们在本文中了解到的有关SQL Server Lead功能的快速摘要:

  • LEAD function get the value from the current row to subsequent row to fetch value LEAD函数从当前行到下一行获取值以获取值
  • We use the sort function to sort data in ascending or descending order 我们使用sort函数对数据进行升序或降序排序
  • We use the PARTITION BY clause to partition data based on the specified expression 我们使用PARTITION BY子句根据指定的表达式对数据进行分区
  • We can specify a default value to avoid NULL value in the output 我们可以指定一个默认值以避免输出中出现NULL值
  • We can also address complex scnenarios with CTEs and expressions using SQL Server Lead function 我们还可以使用SQL Server Lead函数通过CTE和表达式解决复杂的问题

翻译自: https://www.sqlshack.com/overview-and-examples-of-sql-server-lead-function/

sql示例

sql示例_SQL Server Lead功能概述和示例相关推荐

  1. sql limit 子句_SQL Server TOP子句概述和示例

    sql limit 子句 This article explores the SQL Server TOP clause using various examples, along the way, ...

  2. sql计数_SQL计数区分功能概述

    sql计数 This article explores SQL Count Distinct operator for eliminating the duplicate rows in the re ...

  3. merge语句_SQL Server MERGE语句概述和示例

    merge语句 In this article, we will review SQL Server MERGE statement, alternatives to MERGE statement, ...

  4. sql 自定义函数 示例_SQL Server SESSION_CONTEXT()函数与示例

    sql 自定义函数 示例 This article explores the SQL Server session context function, SESSION_CONTEXT() and pe ...

  5. soar ddl审核规范_SQL Server审核功能– DDL事件审核示例

    soar ddl审核规范 介绍 (Introduction) In a previous article "SQL Server Audit feature – discovery and ...

  6. SQL Server舍入功能概述– SQL舍入,上限和下限

    Developers deal with numerous data types on a day- to-day basis. We need to change the data type or ...

  7. sql server 替换_SQL Server替换功能–全面指南

    sql server 替换 Hello, readers! In this article, we will be understanding the working of SQL Server Re ...

  8. sql server 群集_SQL Server群集索引概述

    sql server 群集 This article targets the beginners and gives an introduction of the clustered index in ...

  9. sql 自定义函数 示例_SQL Server Choose()函数介绍和示例

    sql 自定义函数 示例 In the article, a CASE statement in SQL, we explored one of the important logical expre ...

最新文章

  1. tensorflow 安装_tensorflow安装
  2. 思科cisco解决方案:思科ACI解决方案和Nexus_9000交换机
  3. 关于SAP物流和供应链模块发展的一点思考
  4. 我的家乡-客家小山村
  5. Android之旅---广播(BroadCast)
  6. 微软的创新还是败笔?Windows 8为苹果创造天赐良机
  7. pg_resetxlog清理的pg_xlog下的WAL日志
  8. [UE4]响应鼠标点击
  9. 一朝不知IP事,一世妄为测试人...
  10. 某IDC服务商机房宕机致银行业务中断 银监会发布风险提示
  11. java语言介绍及特点分析(萌新入门须知内容)
  12. HTML禁用浏览器后退功能
  13. 技术分享 | 大量 Opening tables 案例分析
  14. Python爬取URP教务系统课程表并保存到excel
  15. 2021年低压电工及低压电工证考试
  16. 运动学习与控制-学习笔记(三)——运动控制理论
  17. 对于iphone X 兼容性处理的css适配方法和js适配方法
  18. Java实现 LeetCode 400 第N个数字
  19. 响应式Web设计(四):响应式Web设计的优化
  20. HTML5方方面面的活动报道,大家来吐槽啊

热门文章

  1. python web环境傻瓜搭建_Python 环境搭建以及神器推荐,果断收藏!
  2. 清华大学 ucore-lab0 MacOS
  3. 项目Alpha冲刺(团队)-第九天冲刺
  4. 为什么SQL用UPDATE语句更新时更新行数会多3行有触发器有触发器有触发器有触发器有触发器有触发器...
  5. Excel自动换行、Export2Excel 自动换行
  6. [POI2004]GRA
  7. css3导航渐变 滑过显示动画
  8. VSCode 设置代码自动保存!!!
  9. htaccess有什么用
  10. 个人所得税的申报方式有两种,分别有什么区别?该怎么选?