COUNT (Transact-SQL)COUNT (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
この関数は、グループ内で見つかった項目数を返します。This function returns the number of items found in a group. COUNT
は COUNT_BIG 関数と同じように動作します。COUNT
operates like the COUNT_BIG function. これらの関数の違いは、戻り値のデータ型のみです。These functions differ only in the data types of their return values. COUNT
は常に int データ型の値を返します。COUNT
always returns an int data type value. COUNT_BIG
は常に bigint データ型の値を返します。COUNT_BIG
always returns a bigint data type value.
Transact-SQL 構文表記規則
Transact-SQL Syntax Conventions
構文Syntax
-- Aggregation Function Syntax
COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )
-- Analytic Function Syntax
COUNT ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )
注意
SQL Server 2014 以前の Transact-SQL 構文を確認するには、以前のバージョンのドキュメントを参照してください。To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
引数Arguments
ALLALL
すべての値にこの集計関数を適用します。Applies the aggregate function to all values. 既定として ALL が使用されます。ALL serves as the default.
DISTINCTDISTINCT
COUNT
で一意の NULL ではない値の数を返すことを指定します。Specifies that COUNT
returns the number of unique nonnull values.
式 (expression)expression
image、ntext、text を除く、任意の型の 式です。An expression of any type, except image, ntext, or text. COUNT
は、式の集計関数またはサブクエリをサポートしていません。Note that COUNT
does not support aggregate functions or subqueries in an expression.
*
COUNT
ですべての行をカウントし、返すテーブルの合計行数を決定することを指定します。Specifies that COUNT
should count all rows to determine the total table row count to return. COUNT(*)
はパラメーターを受け取らず、DISTINCT の使用をサポートしていません。COUNT(*)
takes no parameters and does not support the use of DISTINCT. COUNT(*)
では、この関数の定義上、特定の列についての情報は使用されないため、expression パラメーターは必要ありません。COUNT(*)
does not require an expression parameter because by definition, it does not use information about any particular column. COUNT(*)
は、指定されたテーブル内の行数を返し、重複する行を保持します。COUNT(*)
returns the number of rows in a specified table, and it preserves duplicate rows. 各行は 1 行としてカウントされ、It counts each row separately. これには NULL 値を保持している行も含まれます。This includes rows that contain null values.
OVER ( [ partition_by_clause ] [ order_by_clause ] [ ROW_or_RANGE_clause ] )OVER ( [ partition_by_clause ] [ order_by_clause ] [ ROW_or_RANGE_clause ] )
partition_by_clause は、FROM
句で生成された結果セットをパーティションに分割します。このパーティションに COUNT
関数が適用されます。The partition_by_clause divides the result set produced by the FROM
clause into partitions to which the COUNT
function is applied. 指定しない場合、関数ではクエリ結果セットのすべての行を 1 つのグループとして扱います。If not specified, the function treats all rows of the query result set as a single group. order_by_clause は、操作の論理的順序を決定します。The order_by_clause determines the logical order of the operation. 詳細については、OVER 句 (Transact-SQL) に関するページを参照してください。See OVER Clause (Transact-SQL) for more information.
戻り値の型Return types
intint
解説Remarks
COUNT(*) はグループ内のアイテム数を返します。COUNT(*) returns the number of items in a group. これには NULL 値と重複値が含まれます。This includes NULL values and duplicates.
COUNT(ALL expression) はグループ内の各行に対して expression を評価し、非 NULL 値の数を返します。COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression) はグループ内の各行に対して expression を評価し、一意の非 NULL 値の数を返します。COUNT(DISTINCT expression) evaluates expression for each row in a group, and returns the number of unique, nonnull values.
戻り値が 2^31-1 を超える場合、COUNT
はエラーを返します。For return values exceeding 2^31-1, COUNT
returns an error. このような場合は代わりに COUNT_BIG
を使用してください。For these cases, use COUNT_BIG
instead.
COUNT
は、OVER および ORDER BY 句 "*なし " で使用される場合は決定的関数です。COUNT
is a deterministic function when used *without _ the OVER and ORDER BY clauses. OVER および ORDER BY 句と "*共に*_" 使用される場合は、非決定的関数です。It is nondeterministic when used with the OVER and ORDER BY clauses. 詳細については、「決定的関数と非決定的関数」を参照してください。See Deterministic and Nondeterministic Functions for more information.
例Examples
A.A. COUNT と DISTINCT を使用するUsing COUNT and DISTINCT
この例では、Adventure Works CyclesAdventure Works Cycles の従業員が保持できるさまざまな役職の数を返します。This example returns the number of different titles that an Adventure Works CyclesAdventure Works Cycles employee can hold.
SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO
結果セットは次のようになります。Here is the result set.
-----------
67
(1 row(s) affected)
B.B. COUNT(_) を使用するUsing COUNT(_)
この例は、Adventure Works CyclesAdventure Works Cycles の従業員の合計数を返します。This example returns the total number of Adventure Works CyclesAdventure Works Cycles employees.
SELECT COUNT(*)
FROM HumanResources.Employee;
GO
結果セットは次のようになります。Here is the result set.
-----------
290
(1 row(s) affected)
C.C. COUNT(*) を他の集計関数と共に使用するUsing COUNT(*) with other aggregates
この例は、COUNT(*)
が SELECT
リスト内の他の集計関数と連携していることを示しています。This example shows that COUNT(*)
works with other aggregate functions in the SELECT
list. この例では、AdventureWorks2012AdventureWorks2012 データベースを使用します。The example uses the AdventureWorks2012AdventureWorks2012 database.
SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO
結果セットは次のようになります。Here is the result set.
----------- ---------------------
14 3472.1428
(1 row(s) affected)
D.D. OVER 句を使用するUsing the OVER clause
この例では、MIN
、MAX
、AVG
、および COUNT
関数と OVER
句を使用して、AdventureWorks2012AdventureWorks2012 データベースの HumanResources.Department
テーブルの各部門について集計値を返します。This example uses the MIN
, MAX
, AVG
and COUNT
functions with the OVER
clause, to return aggregated values for each department in the AdventureWorks2012AdventureWorks2012 database HumanResources.Department
table.
SELECT DISTINCT Name
, MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
, MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
, AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;
結果セットは次のようになります。Here is the result set.
Name MinSalary MaxSalary AvgSalary EmployeesPerDept
----------------------------- --------------------- --------------------- --------------------- ----------------
Document Control 10.25 17.7885 14.3884 5
Engineering 32.6923 63.4615 40.1442 6
Executive 39.06 125.50 68.3034 4
Facilities and Maintenance 9.25 24.0385 13.0316 7
Finance 13.4615 43.2692 23.935 10
Human Resources 13.9423 27.1394 18.0248 6
Information Services 27.4038 50.4808 34.1586 10
Marketing 13.4615 37.50 18.4318 11
Production 6.50 84.1346 13.5537 195
Production Control 8.62 24.5192 16.7746 8
Purchasing 9.86 30.00 18.0202 14
Quality Assurance 10.5769 28.8462 15.4647 6
Research and Development 40.8654 50.4808 43.6731 4
Sales 23.0769 72.1154 29.9719 18
Shipping and Receiving 9.00 19.2308 10.8718 6
Tool Design 8.62 29.8462 23.5054 6
(16 row(s) affected)
例: Azure Synapse AnalyticsAzure Synapse Analytics、Parallel Data WarehouseParallel Data WarehouseExamples: Azure Synapse AnalyticsAzure Synapse Analytics and Parallel Data WarehouseParallel Data Warehouse
E.E. COUNT と DISTINCT を使用するUsing COUNT and DISTINCT
この例では、特定の会社の従業員が保持できるさまざまな役職の数を返します。This example returns the number of different titles that an employee of a specific company can hold.
USE ssawPDW;
SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;
結果セットは次のようになります。Here is the result set.
-----------
67
F.F. COUNT(*) を使用するUsing COUNT(*)
この例は、dbo.DimEmployee
テーブルの合計行数を返します。This example returns the total number of rows in the dbo.DimEmployee
table.
USE ssawPDW;
SELECT COUNT(*)
FROM dbo.DimEmployee;
結果セットは次のようになります。Here is the result set.
-------------
296
G.G. COUNT(*) を他の集計関数と共に使用するUsing COUNT(*) with other aggregates
この例では、COUNT(*)
と、SELECT
リスト内の他の集計関数を組み合わせています。This example combines COUNT(*)
with other aggregate functions in the SELECT
list. 年間販売ノルマが $500,000 より多い販売担当者の数と、販売担当者の平均販売ノルマを返します。It returns the number of sales representatives with an annual sales quota greater than $500,000, and the average sales quota of those sales representatives.
USE ssawPDW;
SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;
結果セットは次のようになります。Here is the result set.
TotalCount Average Sales Quota
---------- -------------------
10 683800.0000
H.H. HAVING で COUNT を使用するUsing COUNT with HAVING
この例では、COUNT
と HAVING
句を使用して、従業員数が 15 人を超える会社の部門を返します。This example uses COUNT
with the HAVING
clause to return the departments of a company, each of which has more than 15 employees.
USE ssawPDW;
SELECT DepartmentName,
COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;
結果セットは次のようになります。Here is the result set.
DepartmentName EmployeesInDept
-------------- ---------------
Sales 18
Production 179
I.I. OVER で COUNT を使用するUsing COUNT with OVER
この例では、COUNT
と OVER
句を使用して、指定した各受注に含まれる製品数を返します。This example uses COUNT
with the OVER
clause, to return the number of products contained in each of the specified sales orders.
USE ssawPDW;
SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
,SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');
結果セットは次のようになります。Here is the result set.
ProductCount SalesOrderID`
------------ -----------------
3 SO53115
1 SO55981
関連項目See also
集計関数 (Transact-SQL)Aggregate Functions (Transact-SQL)
COUNT_BIG (Transact-SQL)COUNT_BIG (Transact-SQL)
OVER 句 (Transact-SQL)OVER Clause (Transact-SQL)