ROW_NUMBER (Transact-SQL)ROW_NUMBER (Transact-SQL)
SQL Server
Azure SQL Database
Azure Synapse Analytics (SQL DW)
Parallel Data Warehouse
SQL Server
Azure SQL Database
Azure Synapse Analytics (SQL DW)
Parallel Data Warehouse
結果セットの出力に番号を設定します。Numbers the output of a result set. 具体的には、結果セットのパーティション内の行について、各パーティションの最初の行を 1 とした連続する数値を返します。More specifically, returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
ROW_NUMBER
と RANK
は似ています。ROW_NUMBER
and RANK
are similar. ROW_NUMBER
は、すべての行に順番に番号を付けます (たとえば 1、2、3、4、5)。ROW_NUMBER
numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK
は、同順位に対して同じ番号を付けます (たとえば 1、2、2、4、5)。RANK
provides the same numeric value for ties (for example 1, 2, 2, 4, 5).
注意
ROW_NUMBER
は、クエリの実行時に計算される一時的な値です。ROW_NUMBER
is a temporary value calculated when the query is run. 番号をテーブルに保持するには、「IDENTITY プロパティ」と「SEQUENCE」をご覧ください。To persist numbers in a table, see IDENTITY Property and SEQUENCE.
Transact-SQL 構文表記規則
Transact-SQL Syntax Conventions
構文Syntax
ROW_NUMBER ( )
OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )
引数Arguments
PARTITION BY value_expressionPARTITION BY value_expression
FROM 句で生成された結果セットを、ROW_NUMBER 関数が適用されるパーティションに分割します。Divides the result set produced by the FROM clause into partitions to which the ROW_NUMBER function is applied. value_expression は、結果セットをパーティションに分割するときに使用する列を指定します。value_expression specifies the column by which the result set is partitioned. PARTITION BY
を指定しない場合、関数ではクエリ結果セットのすべての行を 1 つのグループとして扱います。If PARTITION BY
is not specified, the function treats all rows of the query result set as a single group. 詳しくは、OVER 句 (Transact-SQL) に関する記事をご覧ください。For more information, see OVER Clause (Transact-SQL).
order_by_clauseorder_by_clause
ORDER BY
句は、指定したパーティション内の行に一意の ROW_NUMBER
を割り当てる順序を決定します。The ORDER BY
clause determines the sequence in which the rows are assigned their unique ROW_NUMBER
within a specified partition. この引数は必須です。It is required. 詳細については、OVER 句 (Transact-SQL)を参照してください。For more information, see OVER Clause (Transact-SQL).
戻り値の型Return Types
bigintbigint
全般的な解説General Remarks
以下の条件が満たされている場合を除き、ROW_NUMBER()
を使用したクエリによって返される行が、実行ごとにまったく同じ順序になるという保証はありません。There is no guarantee that the rows returned by a query using ROW_NUMBER()
will be ordered exactly the same with each execution unless the following conditions are true.
パーティション分割された行の値が一意である。Values of the partitioned column are unique.
ORDER BY
列の値が一意である。Values of theORDER BY
columns are unique.パーティション分割された列と
ORDER BY
列の値の組み合わせが一意である。Combinations of values of the partition column andORDER BY
columns are unique.
ROW_NUMBER()
は非決定的です。ROW_NUMBER()
is nondeterministic. 詳細については、「 決定的関数と非決定的関数」を参照してください。For more information, see Deterministic and Nondeterministic Functions.
使用例Examples
A.A. 簡単な例Simple examples
次のクエリは、4 つのシステム テーブルをアルファベット順に返します。The following query returns the four system tables in alphabetic order.
SELECT
name, recovery_model_desc
FROM sys.databases
WHERE database_id < 5
ORDER BY name ASC;
以下に結果セットを示します。Here is the result set.
NAMEname | recovery_model_descrecovery_model_desc |
---|---|
mastermaster | SIMPLESIMPLE |
modelmodel | FULLFULL |
msdbmsdb | SIMPLESIMPLE |
tempdbtempdb | SIMPLESIMPLE |
各行の前に行番号列を追加するには、ROW_NUMBER
関数で列 (ここでは Row#
という名前) を追加します。To add a row number column in front of each row, add a column with the ROW_NUMBER
function, in this case named Row#
. ORDER BY
句を OVER
句まで移動する必要があります。You must move the ORDER BY
clause up to the OVER
clause.
SELECT
ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#,
name, recovery_model_desc
FROM sys.databases
WHERE database_id < 5;
以下に結果セットを示します。Here is the result set.
Row#Row# | NAMEname | recovery_model_descrecovery_model_desc |
---|---|---|
11 | mastermaster | SIMPLESIMPLE |
22 | modelmodel | FULLFULL |
33 | msdbmsdb | SIMPLESIMPLE |
44 | tempdbtempdb | SIMPLESIMPLE |
recovery_model_desc
列に PARTITION BY
句を追加すると、recovery_model_desc
値が変更されたときに番号付けが再開されます。Adding a PARTITION BY
clause on the recovery_model_desc
column, will restart the numbering when the recovery_model_desc
value changes.
SELECT
ROW_NUMBER() OVER(PARTITION BY recovery_model_desc ORDER BY name ASC)
AS Row#,
name, recovery_model_desc
FROM sys.databases WHERE database_id < 5;
以下に結果セットを示します。Here is the result set.
Row#Row# | NAMEname | recovery_model_descrecovery_model_desc |
---|---|---|
11 | modelmodel | FULLFULL |
11 | mastermaster | SIMPLESIMPLE |
22 | msdbmsdb | SIMPLESIMPLE |
33 | tempdbtempdb | SIMPLESIMPLE |
B.B. 販売員の行番号を返すReturning the row number for salespeople
次の例では、Adventure Works CyclesAdventure Works Cycles の販売員について、今年に入ってからの売り上げ順位に基づく行番号を返します。The following example calculates a row number for the salespeople in Adventure Works CyclesAdventure Works Cycles based on their year-to-date sales ranking.
USE AdventureWorks2012;
GO
SELECT ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row,
FirstName, LastName, ROUND(SalesYTD,2,1) AS "Sales YTD"
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;
以下に結果セットを示します。Here is the result set.
Row FirstName LastName SalesYTD
--- ----------- ---------------------- -----------------
1 Linda Mitchell 4251368.54
2 Jae Pak 4116871.22
3 Michael Blythe 3763178.17
4 Jillian Carson 3189418.36
5 Ranjit Varkey Chudukatil 3121616.32
6 José Saraiva 2604540.71
7 Shu Ito 2458535.61
8 Tsvi Reiter 2315185.61
9 Rachel Valdez 1827066.71
10 Tete Mensa-Annan 1576562.19
11 David Campbell 1573012.93
12 Garrett Vargas 1453719.46
13 Lynn Tsoflias 1421810.92
14 Pamela Ansman-Wolfe 1352577.13
C.C. 行のサブセットを返すReturning a subset of rows
次の例では、SalesOrderHeader
テーブル内のすべての行の行番号を OrderDate
の順序で計算し、50
から 60
までの行のみを返します。The following example calculates row numbers for all rows in the SalesOrderHeader
table in the order of the OrderDate
and returns only rows 50
to 60
inclusive.
USE AdventureWorks2012;
GO
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
FROM Sales.SalesOrderHeader
)
SELECT SalesOrderID, OrderDate, RowNumber
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;
D.D. ROW_NUMBER() を PARTITION と共に使用するUsing ROW_NUMBER() with PARTITION
次の例では、PARTITION BY
引数を使用して、列 TerritoryName
を基準にクエリ結果セットをパーティションに分割します。The following example uses the PARTITION BY
argument to partition the query result set by the column TerritoryName
. ORDER BY
句に指定した OVER
句によって、列 SalesYTD
を基準に各パーティション内の行の順序付けが行われます。The ORDER BY
clause specified in the OVER
clause orders the rows in each partition by the column SalesYTD
. ORDER BY
ステートメントの SELECT
句によって、TerritoryName
を基準にクエリ結果セット全体の順序付けが行われます。The ORDER BY
clause in the SELECT
statement orders the entire query result set by TerritoryName
.
USE AdventureWorks2012;
GO
SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2,1) AS SalesYTD,
ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC)
AS Row
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0
ORDER BY TerritoryName;
以下に結果セットを示します。Here is the result set.
FirstName LastName TerritoryName SalesYTD Row
--------- -------------------- ------------------ ------------ ---
Lynn Tsoflias Australia 1421810.92 1
José Saraiva Canada 2604540.71 1
Garrett Vargas Canada 1453719.46 2
Jillian Carson Central 3189418.36 1
Ranjit Varkey Chudukatil France 3121616.32 1
Rachel Valdez Germany 1827066.71 1
Michael Blythe Northeast 3763178.17 1
Tete Mensa-Annan Northwest 1576562.19 1
David Campbell Northwest 1573012.93 2
Pamela Ansman-Wolfe Northwest 1352577.13 3
Tsvi Reiter Southeast 2315185.61 1
Linda Mitchell Southwest 4251368.54 1
Shu Ito Southwest 2458535.61 2
Jae Pak United Kingdom 4116871.22 1
例: Azure Synapse Analytics (SQL DW)Azure Synapse Analytics (SQL DW) および Parallel Data WarehouseParallel Data WarehouseExamples: Azure Synapse Analytics (SQL DW)Azure Synapse Analytics (SQL DW) and Parallel Data WarehouseParallel Data Warehouse
E.E. 販売員の行番号を返すReturning the row number for salespeople
次の例は、割り当てられている販売ノルマに基づいて営業担当者の ROW_NUMBER
を返します。The following example returns the ROW_NUMBER
for sales representatives based on their assigned sales quota.
-- Uses AdventureWorks
SELECT ROW_NUMBER() OVER(ORDER BY SUM(SalesAmountQuota) DESC)
AS RowNumber,
FirstName, LastName,
CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
ON e.EmployeeKey = sq.EmployeeKey
WHERE e.SalesPersonFlag = 1
GROUP BY LastName, FirstName;
次に結果セットの一部を示します。Here is a partial result set.
RowNumber FirstName LastName SalesQuota
--------- --------- ------------------ -------------
1 Jillian Carson 12,198,000.00
2 Linda Mitchell 11,786,000.00
3 Michael Blythe 11,162,000.00
4 Jae Pak 10,514,000.00
F.F. ROW_NUMBER() を PARTITION と共に使用するUsing ROW_NUMBER() with PARTITION
次の例では、ROW_NUMBER
関数を PARTITION BY
引数と共に使用します。The following example shows using the ROW_NUMBER
function with the PARTITION BY
argument. これにより、ROW_NUMBER
関数は各パーティション内の行に番号を付けます。This causes the ROW_NUMBER
function to number the rows in each partition.
-- Uses AdventureWorks
SELECT ROW_NUMBER() OVER(PARTITION BY SalesTerritoryKey
ORDER BY SUM(SalesAmountQuota) DESC) AS RowNumber,
LastName, SalesTerritoryKey AS Territory,
CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
ON e.EmployeeKey = sq.EmployeeKey
WHERE e.SalesPersonFlag = 1
GROUP BY LastName, FirstName, SalesTerritoryKey;
次に結果セットの一部を示します。Here is a partial result set.
RowNumber LastName Territory SalesQuota
--------- ------------------ --------- -------------
1 Campbell 1 4,025,000.00
2 Ansman-Wolfe 1 3,551,000.00
3 Mensa-Annan 1 2,275,000.00
1 Blythe 2 11,162,000.00
1 Carson 3 12,198,000.00
1 Mitchell 4 11,786,000.00
2 Ito 4 7,804,000.00
参照See Also
RANK (Transact-SQL) RANK (Transact-SQL)
DENSE_RANK (Transact-SQL) DENSE_RANK (Transact-SQL)
NTILE (Transact-SQL)NTILE (Transact-SQL)
フィードバック
フィードバックを読み込んでいます...