ylbtech-SQL-W3School- function: SQL COUNT () function |
1. Back to top |
COUNT () function returns the number of rows that match specified criteria.
SQL COUNT () syntax
SQL COUNT (column_name) Syntax
COUNT (column_name) function returns the value of the specified number of columns ( NULL not included ):
SELECT COUNT(column_name) FROM table_name
SQL COUNT (*) syntax
COUNT (*) function returns the number of records in the table:
SELECT COUNT(*) FROM table_name
SQL COUNT (DISTINCT column_name) Syntax
COUNT (DISTINCT column_name) function returns the number of different values of the specified column :
SELECT COUNT(DISTINCT column_name) FROM table_name
Notes: COUNT (DISTINCT) applies to ORACLE and Microsoft SQL Server, but can not be used in Microsoft Access.
SQL COUNT (column_name) example
We have the following "Orders" table:
O_Id | OrderDate | OrderPrice | Customer |
---|---|---|---|
1 | 2008/12/29 | 1000 | Bush |
2 | 2008/11/23 | 1600 | Carter |
3 | 2008/10/05 | 700 | Bush |
4 | 2008/09/28 | 300 | Bush |
5 | 2008/08/06 | 2000 | Adams |
6 | 2008/07/21 | 100 | Carter |
Now, we want to count customers "Carter" number of orders.
We use the following SQL statement:
SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Carter'
SQL statement is the result of more than 2, because customers Carter a total of two orders:
CustomerNilsen |
---|
2 |
If we omit the WHERE clause, like this:
SELECT COUNT(*) AS NumberOfOrders FROM Orders
The result set will look like this:
NumberOfOrders |
---|
6 |
This is the total number of rows in the table.
SQL COUNT (DISTINCT column_name) example
Now, we want to count the number of different customers table "Orders".
We use the following SQL statement:
SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders
The result set will look like this:
NumberOfCustomers |
---|
3 |
This is the number of different customers (Bush, Carter and Adams) of the "Orders" table.
2. Return to top |
3. Back to top |
4. Top |
5. Top |
6. Back to top |
Author: ylbtech Source: http://ylbtech.cnblogs.com/ This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise reserves the right to pursue legal responsibilities. |