LAG (Transact-SQL)LAG (Transact-SQL)
適用対象:Applies to: SQL ServerSQL Server (サポートされているすべてのバージョン)
SQL ServerSQL Server (all supported versions)
Azure SQL データベースAzure SQL Database
Azure SQL データベースAzure SQL Database
Azure SQL Managed InstanceAzure SQL Managed Instance
Azure SQL Managed InstanceAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
SQL ServerSQL Server (サポートされているすべてのバージョン)
SQL ServerSQL Server (all supported versions)
Azure SQL データベースAzure SQL Database
Azure SQL データベースAzure SQL Database
Azure SQL Managed InstanceAzure SQL Managed Instance
Azure SQL Managed InstanceAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
SQL Server 2012 (11.x)SQL Server 2012 (11.x) で開始する自己結合を使用せずに同じ結果セットの前の行からデータにアクセスします。Accesses data from a previous row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x)SQL Server 2012 (11.x). LAG によって、現在の行の前にある指定された物理的なオフセットの行にアクセスできます。LAG provides access to a row at a given physical offset that comes before the current row. SELECT ステートメントでこの分析関数を使用して、現在の行の値と前の行の値を比較します。Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.
Transact-SQL 構文表記規則 (Transact-SQL)
Transact-SQL Syntax Conventions (Transact-SQL)
構文Syntax
LAG (scalar_expression [,offset] [,default])
OVER ( [ partition_by_clause ] order_by_clause )
注意
SQL Server 2014 以前の Transact-SQL 構文を確認するには、以前のバージョンのドキュメントを参照してください。To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
引数Arguments
scalar_expressionscalar_expression
指定されたオフセットに基づいて返される値。The value to be returned based on the specified offset. 単一の (スカラー) 値を返す任意の型の式です。It is an expression of any type that returns a single (scalar) value. scalar_expression は分析関数にはなりません。scalar_expression cannot be an analytic function.
offsetoffset
値を取得する現在の行から戻る行の数。The number of rows back from the current row from which to obtain a value. 指定しない場合は、1 が既定値です。If not specified, the default is 1. offset は、列、サブクエリ、または正の整数と評価されたり、暗黙的に bigint に変換される可能性があるその他の式です。offset can be a column, subquery, or other expression that evaluates to a positive integer or can be implicitly converted to bigint. offset は、負の値または分析関数にはなりません。offset cannot be a negative value or an analytic function.
defaultdefault
offset がパーティションの範囲外である場合に返される値。The value to return when offset is beyond the scope of the partition. 既定値を指定しない場合、NULL が返されます。If a default value is not specified, NULL is returned. default には、列、サブクエリ、または式を指定できますが、分析関数は指定できません。default can be a column, subquery, or other expression, but it cannot be an analytic function. default には、scalar_expression の型との互換性が必要です。default must be type-compatible with scalar_expression.
OVER ( [ partition_by_clause ] order_by_clause )OVER ( [ partition_by_clause ] order_by_clause)
partition_by_clause は、FROM 句で生成された結果セットをパーティションに分割します。このパーティションに関数が適用されます。partition_by_clause divides the result set produced by the FROM clause into partitions to which the function is applied. 指定しない場合、関数ではクエリ結果セットのすべての行を 1 つのグループとして扱います。If not specified, the function treats all rows of the query result set as a single group. order_by_clause は、関数を適用する前にデータの順序を決定します。order_by_clause determines the order of the data before the function is applied. partition_by_clause を指定した場合、この引数によってパーティション内のデータの順序が決定されます。If partition_by_clause is specified, it determines the order of the data in the partition. order_by_clause が必要です。The order_by_clause is required. 詳細については、を参照してください。 OVER 句 (Transact-SQL).For more information, see OVER Clause (Transact-SQL).
戻り値の型Return Types
指定した scalar_expression のデータ型。The data type of the specified scalar_expression. scalar_expression が NULL 値を許容するか default が NULL に設定されている場合は、NULL が返されます。NULL is returned if scalar_expression is nullable or default is set to NULL.
全般的な解説General Remarks
LAG は非決定的です。LAG is nondeterministic. 詳細については、「 決定的関数と非決定的関数」を参照してください。For more information, see Deterministic and Nondeterministic Functions.
例Examples
A.A. 年間の値を比較するCompare values between years
次の例では、LAG 関数を使用して、過去数年間にわたる特定の従業員の販売ノルマの差を返します。The following example uses the LAG function to return the difference in sales quotas for a specific employee over previous years. 最初の行に使用できるラグ値がないため、既定のゼロ (0) が返されることに注意してください。Notice that because there is no lag value available for the first row, the default of zero (0) is returned.
USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
LAG(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS PreviousQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');
結果セットは次のようになります。Here is the result set.
BusinessEntityID SalesYear CurrentQuota PreviousQuota
---------------- ----------- --------------------- ---------------------
275 2005 367000.00 0.00
275 2005 556000.00 367000.00
275 2006 502000.00 556000.00
275 2006 550000.00 502000.00
275 2006 1429000.00 550000.00
275 2006 1324000.00 1429000.00
B.B. パーティション内の値を比較するCompare values within partitions
次の例では、LAG 関数を使用して、従業員間の今年に入ってからの売上高を比較します。The following example uses the LAG function to compare year-to-date sales between employees. PARTITION BY 句を指定して、販売区域ごとに結果セットの行を分割します。The PARTITION BY clause is specified to divide the rows in the result set by sales territory. LAG 関数は各パーティションに対して個別に適用され、各パーティションで計算が再開されます。The LAG function is applied to each partition separately and computation restarts for each partition. OVER 句の ORDER BY 句によって、各パーティション内の行の順序が決められます。The ORDER BY clause in the OVER clause orders the rows in each partition. SELECT ステートメントの ORDER BY 句によって、結果セット全体で行の並べ替えが行われます。The ORDER BY clause in the SELECT statement sorts the rows in the whole result set. 各パーティションの最初の行に使用できるラグ値がないため、既定のゼロ (0) が返されることに注意してください。Notice that because there is no lag value available for the first row of each partition, the default of zero (0) is returned.
USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
LAG (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS PrevRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;
結果セットは次のようになります。Here is the result set.
TerritoryName BusinessEntityID SalesYTD PrevRepSales
----------------------- ---------------- --------------------- ---------------------
Canada 282 2604540.7172 0.00
Canada 278 1453719.4653 2604540.7172
Northwest 284 1576562.1966 0.00
Northwest 283 1573012.9383 1576562.1966
Northwest 280 1352577.1325 1573012.9383
C.C. 任意の式を指定するSpecifying arbitrary expressions
次の例では、LAG 関数の構文にさまざまな任意の式を指定する方法を示します。The following example demonstrates specifying a variety of arbitrary expressions in the LAG function syntax.
CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);
SELECT b, c,
LAG(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;
結果セットは次のようになります。Here is the result set.
b c i
----------- ----------- -----------
1 -3 1
2 4 -2
1 NULL 8
3 1 -6
2 NULL NULL
1 5 NULL
例: Azure Synapse AnalyticsAzure Synapse Analytics、Parallel Data WarehouseParallel Data WarehouseExamples: Azure Synapse AnalyticsAzure Synapse Analytics and Parallel Data WarehouseParallel Data Warehouse
D. 四半期の値を比較するD: Compare values between quarters
次の例では、LAG 関数を示します。The following example demonstrates the LAG function. クエリでは、LAG 関数を使用してカレンダー年の過去数四半期にわたる特定の従業員の販売ノルマの差を返します。The query uses the LAG function to return the difference in sales quotas for a specific employee over previous calendar quarters. 最初の行に使用できるラグ値がないため、既定のゼロ (0) が返されることに注意してください。Notice that because there is no lag value available for the first row, the default of zero (0) is returned.
-- Uses AdventureWorks
SELECT CalendarYear, CalendarQuarter, SalesAmountQuota AS SalesQuota,
LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS PrevQuota,
SalesAmountQuota - LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001, 2002)
ORDER BY CalendarYear, CalendarQuarter;
結果セットは次のようになります。Here is the result set.
Year Quarter SalesQuota PrevQuota Diff
---- ------- ---------- --------- -------------
2001 3 28000.0000 0.0000 28000.0000
2001 4 7000.0000 28000.0000 -21000.0000
2001 1 91000.0000 7000.0000 84000.0000
2002 2 140000.0000 91000.0000 49000.0000
2002 3 7000.0000 140000.0000 -70000.0000
2002 4 154000.0000 7000.0000 84000.0000