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

本文详细介绍了SQL中的Lag函数,用于访问前一行数据。Lag函数从SQL Server 2012开始提供,它与Lead函数类似,但访问的是前一行而非后续行。文章通过四个示例展示了Lag函数的用法,包括不带默认值、带有默认值、偏移值为2以及使用PARTITION BY子句的情况。
摘要由CSDN通过智能技术生成

sql 自定义函数 示例

In the article SQL Server Lead function overview and examples, we explored Lead function for performing computational operations on data. This article gives an overview of the SQL Lag function and its comparison with the SQL Lead function.

在“ SQL Server Lead函数概述和示例”一文中 ,我们探讨了Lead函数用于对数据执行计算操作。 本文概述了SQL滞后函数及其与SQL Lead函数的比较。

SQL延迟功能概述 (Overview of SQL Lag function)

We use a Lag() function to access previous rows data as per defined offset value. It is a window function available from SQL Server 2012 onwards. It works similar to a Lead function. In the lead function, we access subsequent rows, but in lag function, we access previous rows. It is a useful function in comparing the current row value from the previous row value.

我们使用Lag()函数根据定义的偏移值访问先前的行数据。 从SQL Server 2012开始,它是一个窗口函数。 它的工作方式类似于Lead功能。 在Lead函数中,我们访问后续行,而在lag函数中,我们访问先前行。 在比较当前行值和前一行值时,此功能很有用。

滞后函数的语法 (Syntax of Lag function)

LAG (scalar_expression [,offset] [,default])  
OVER ( [ partition_by_clause ] order_by_clause )

It uses following arguments.

它使用以下参数。

  • Scalar_expression: We define a column name or expression in this argument. The lag function does calculations on this column. It is a mandatory argument, and we cannot execute the lag function without this

    Scalar_expression:我们在此参数中定义列名称或表达式。 滞后函数在此列上进行计算。 这是一个强制性参数,没有这个我们就无法执行lag函数
  • Offset: We define an integer number in this argument. The lag function uses this argument forgo behind the number of rows (offset). The default value for this argument is one. It is an optional argument

    偏移:我们在此参数中定义一个整数。 滞后函数在行数(偏移量)后面使用此参数。 此参数的默认值为1。 这是一个可选参数
  • Default: Suppose we define an offset, value that does not lie in the boundary of the data. For example, we specified offset value 3 for the first row. A lag function cannot go three rows behind. It displays the default value if specified. If we do not specify any value for this, the lag function displays NULL in the output for out of range values

    默认值:假设我们定义了一个偏移量,该值不位于数据边界内。 例如,我们为第一行指定了偏移值3。 滞后功能不能落后三行。 如果指定,它将显示默认值。 如果我们没有为此指定任何值,则滞后函数在输出中将NULL显示为超出范围的值
  • PARTITION BY: It creates a logical boundary of data. Suppose we have an extensive data set and we require calculations on a smaller set of data, we can define partitions for it. For example, sales data for an organization might contain data for several years. We can create a partition quarterly and do the computation. It is as well an optional argument

    PARTITION BY:它创建数据的逻辑边界。 假设我们有一个广泛的数据集,并且需要对较小的数据集进行计算,则可以为其定义分区。 例如,组织的销售数据可能包含几年的数据。 我们可以每季度创建一个分区并进行计算。 它也是一个可选参数
  • ORDER BY: We can sort data in ascending or descending order using ORDER by clause. By default, it uses ascending order to sort data

    ORDER BY:我们可以使用ORDER by子句对数据进行升序或降序排序。 默认情况下,它使用升序对数据进行排序

We will use data from the previous article for demonstration of SQL Server Lag function as well:

我们还将使用上一篇文章中的数据来演示SQL Server Lag函数:

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')
GO
SELECT * FROM   @Employee;

We have the following data in the Employee table:

我们在Employee表中有以下数据:

Sample data

示例1:不带默认值SQL Lag函数 (Example 1: SQL Lag function without a default value)

Execute the following query to use the Lag function on the JoiningDate column with offset one. We did not specify any default value in this query.

执行以下查询以使用偏移量为1的JoiningDate列上的滞后函数。 我们没有在该查询中指定任何默认值。

Execute the following query (we require to run the complete query along with defining a variable, its value):

执行以下查询(我们需要运行完整的查询以及定义变量及其值):

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

In the output, we can note the following:

在输出中,我们可以注意到以下内容:

  • The first row shows NULL value for the EndDate column because it does not have any previous rows

    第一行显示EndDate列的NULL值,因为它没有任何先前的行
  • The second row contains previous row value in the EndDate column. It takes value from the previous row due to offset value 1

    第二行包含EndDate列中的上一行值。 由于偏移值1,它从上一行获取值

Lag function without a default value

示例2:具有默认值SQL Lag函数 (Example 2: SQL Lag function with a default value)

In the previous example, we get NULL value as a default value. Let’s use a default end date in the lag function. This example also uses offset value 1 in the lag function:

在前面的示例中,我们获得NULL值作为默认值。 让我们在lag函数中使用默认的结束日期。 此示例还在lag函数中使用偏移值1:

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

In the output, we can see a default value instead of NULL in the first row:

在输出中,我们可以在第一行看到默认值而不是NULL:

Lag function with a default value

We can use compatible data types in the default value column. If we use incompatible data types, we get the following error message:

我们可以在默认值列中使用兼容的数据类型。 如果我们使用不兼容的数据类型,则会收到以下错误消息:

Error message

示例3:偏移值为2SQL滞后函数 (Example 3: SQL Lag function with OFFSET value 2)

Previously, we used default offset 1 in Lag function, and it takes value from the previous row. In the example, we use offset value 2. In the output, you can see we have a default value for row 1 and 2. In row 3, it takes value from row 1:

以前,我们在Lag函数中使用默认偏移量1,它从上一行获取值。 在示例中,我们使用偏移值2。在输出中,您可以看到我们为第1行和第2行提供了默认值。在第3行中,它从第1行获取值:

SELECT *, 
       Lag(JoiningDate, 2,'1999-09-01') OVER(
       ORDER BY JoiningDate ASC) AS EndDate
FROM @Employee;

Lag function with OFFSET value 2

示例4:带有PARTITION BY子句SQL滞后函数 (Example 4: SQL Lag function with PARTITION BY clause)

As discussed earlier, we use the PARTITION BY clause to create a logical subset of data. Let’s use this PARTITION function on the ProductSales table. You can refer to the SQL Server Lead function to create this table:

如前所述,我们使用PARTITION BY子句创建数据的逻辑子集。 让我们在ProductSales表上使用此PARTITION函数。 您可以参考SQL Server Lead函数来创建此表:

SQL Server Lag function with PARTITION BY clause

In the following query, we use SQL Server Lag function and view the output:

在以下查询中,我们使用SQL Server滞后函数并查看输出:

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

In the output, the lag function considers all rows as a single data set and applies Lag function:

在输出中,lag函数将所有行视为一个数据集,并应用Lag函数:

SQL Server Lag function with PARTITION BY clause

In the ProductSales table, we have data for the years of 2017, 2018 and 2019. We want to use a lag function on a yearly basis. We use the PARTITION BY clause on the Year column and define the logical subset of data on a yearly basis. We use the Order by clause on year and quarter columns to sort data first on a yearly basis and then monthly:

在ProductSales表中,我们具有2017年,2018年和2019年的数据。我们希望每年使用滞后函数。 我们在Year列上使用PARTITION BY子句,并每年定义数据的逻辑子集。 我们使用“年”和“季度”列上的“排序依据”子句对数据进行逐年排序,然后按月排序:

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

In the following screenshot, we can see three partitions of data for 2017,2018 and 2019 year. The Lag function individually works on each partition and calculates the required data:

在以下屏幕截图中,我们可以看到2017、2018和2019年的三个数据分区。 滞后函数分别在每个分区上工作并计算所需的数据:

Lag function with partition

结论 (Conclusion)

In this article, we learned the SQL Lag function and its usage to retrieve a value from previous rows. Here is the quick summary of the lag function:

在本文中,我们学习了SQL Lag函数及其在前几行中检索值的用法。 这是滞后函数的快速摘要:

  • Lag function fetches the value from the previous rows based on the offset defined

    滞后函数根据定义的偏移量从前几行获取值
  • Offset one is the default offset value, and in this Lag, the function retrieves a value from the previous row

    偏移量一是默认偏移量值,在此延迟中,函数从上一行检索一个值
  • PARTITION BY clause defines a logical boundary of data based on the specified condition

    PARTITION BY子句根据指定条件定义数据的逻辑边界
  • The lag function uses default value NULL for out-of-range data

    滞后函数对超出范围的数据使用默认值NULL
  • We can use the Lag function with common table expression, stored procedures, and functions for computation purposes

    我们可以将Lag函数与公用表表达式,存储过程和函数一起使用,以进行计算

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

sql 自定义函数 示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
收集整理的SQL Server自定义函数,原文地址:http://blog.csdn.net/maco_wang 1.去除字符串中的html标记及标记中的内容 2 2. 去除字符串中连续的分割符 4 3.求第一个字符串中第二个串的个数 6 4.综合模糊查询 6 5.将十进制转成十六进制 8 6.求两个字符串中相同的汉字及字母的个数 10 7.生成n位随机字符串 11 8.取出字符串中的汉字、字母或是数字 14 9.根据字符分割字符串的三种写法 16 10.将数字转换千分位分隔形式 18 11.取汉字首字母的两个函数 20 12.根据身份证得到生日函数 23 13.根据身份证计算性别函数 24 14.将身份证的15位号码升级为18位 25 15.通过身份证获得户籍 27 16.多个数据项的字符串取指定位置字符 28 17.中缀算术转后缀算术表达式并计算的函数 29 18.人民币小写金额转大写 32 19.向左填充指定字符串 36 20.将整型数字转换为大写汉字 39 21.检查给定串是否存在于由区间及点集的结合内 39 22.根据日期返回星座 41 23.计算两个日期之间的工作日 43 24.根据年月生成日历函数 44 25.从第一个汉字开始分割字符串 47 26.过滤掉字符串中重复的字符 47 27.根据日期得到星期的函数 48 28.根据年度判断是否是闰年 49 29.完善SQL农历转换函数 50 30.自定义函数实现位操作 58 31.求某段时间内星期几的天数 61 32.根据进舍位或四舍五入来求值 63 33.字符串转成16进制函数 64 34.去掉字段中多个带区号电话号码前面的区号 65 35.SQL2000/2005字符串拆分为列表通用函数 67 36.求字符串中汉字的个数 69 37.根据年月得到当月的天数 71 38.全角半角转换函数 71
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值