Что такое count в sql
Перейти к содержимому

Что такое count в sql

  • автор:

SQL функция COUNT

В этом учебном материале вы узнаете, как использовать SQL функцию COUNT с синтаксисом и примерами.

Описание

SQL функция COUNT используется для подсчета количества строк, возвращаемых в операторе SELECT.

Синтаксис

Синтаксис для функции COUNT в SQL.

Или синтаксис для функции COUNT при группировке результатов по одному или нескольким столбцам.

Параметры или аргумент

Пример — функция COUNT включает только значения NOT NUL

Не все это понимают, но функция COUNT будет подсчитывать только те записи, в которых expressions НЕ равно NULL в COUNT( expressions ). Когда expressions является значением NULL, оно не включается в вычисления COUNT. Давайте рассмотрим это дальше.

Что такое count в sql

Analytic Functions for information on syntax, semantics, and restrictions

COUNT returns the number of rows returned by the query. You can use it as an aggregate or analytic function.

If you specify DISTINCT , then you can specify only the query_partition_clause of the analytic_clause . The order_by_clause and windowing_clause are not allowed.

If you specify expr , then COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr .

If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls. COUNT never returns null.

Before performing a COUNT (DISTINCT expr ) operation on a large amount of data, consider using one of the following methods to obtain approximate results more quickly than exact results:

Set the APPROX_FOR_COUNT_DISTINCT initialization parameter to true before using the COUNT (DISTINCT expr ) function. Refer to Oracle Database Reference for more information on this parameter.

Use the APPROX_COUNT_DISTINCT function instead of the COUNT (DISTINCT expr ) function. Refer to APPROX_COUNT_DISTINCT.

«About SQL Expressions» for information on valid forms of expr and Aggregate Functions

Appendix C in Oracle Database Globalization Support Guide for the collation determination rules, which define the collation COUNT uses to compare character values for the DISTINCT clause

The following examples use COUNT as an aggregate function:

The following example calculates, for each employee in the employees table, the moving count of employees earning salaries in the range 50 less than through 150 greater than the employee’s salary.

Функция COUNT() в SQL

Функция COUNT() подсчитывает количество строк в таблице. Например:

Здесь мы подсчитываем и возвращаем количество строк в таблице Customers.

Использование псевдонимов с функцией COUNT()

В примере выше на выходе мы получили столбец с именем COUNT(*) . Мы можем изменить его название с помощью оператора AS. Например:

Теперь у нас есть столбец total_customers вместо COUNT(*) .

Функция COUNT() с оператором WHERE

Рассмотрим пример использования функции COUNT() с оператором WHERE:

Здесь мы выводим количество клиентов из Великобритании (UK).

Функция COUNT() с оператором DISTINCT

Если нам нужно подсчитать количество уникальных строк (без дублей), то мы можем использовать функцию COUNT() с оператором DISTINCT. Например:

Здесь мы выводим количество уникальных стран.

Функция COUNT() с оператором GROUP BY

Функция COUNT() может использоваться с оператором GROUP BY для подсчета строк с похожими значениями. Например:

Здесь мы подсчитываем и выводим количество клиентов в каждой стране.

Функция COUNT() с оператором HAVING

Рассмотрим пример использования функции COUNT() с оператором HAVING:

Здесь мы подсчитываем количество клиентов, группируя их по странам (country), а затем выводим, если в каждой стране их насчитывается больше 1.

Функция COUNT() со значениями NULL

SELECT COUNT(*) возвращает количество всех строк, независимо от значений NULL (т.е. вместе с ними).

SELECT COUNT(attribute) возвращает количество строк, содержащих ненулевые значения в указанном столбце.

SQL COUNT() Function

The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:

SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:

SQL COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:

Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID
10265 7 2 1996-07-25 1
10266 87 3 1996-07-26 3
10267 25 4 1996-07-29 1

SQL COUNT(column_name) Example

The following SQL statement counts the number of orders from "CustomerID"=7 from the "Orders" table:

Example

SQL COUNT(*) Example

The following SQL statement counts the total number of orders in the "Orders" table:

Example

SQL COUNT(DISTINCT column_name) Example

The following SQL statement counts the number of unique customers in the "Orders" table:

Example

W3SCHOOLS EXAMS

COLOR PICKER

SHARE THIS PAGE

LEARN MORE:

Your Suggestion:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top 10 Tutorials
Top 10 References
Top 10 Examples
Web Certificates

W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2016 by Refsnes Data. All Rights Reserved.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *