Oracle Function:COUNT

Description

The Oracle/PLSQL COUNT function returns the count of an expression.

 The COUNT(*) function

returns the number of rows in a table that satisfy the criteria of the SELECT statement,

 including duplicate rows and rows containing null values in any of the columns.

If a WHERE clause is included in the SELECT statement,

COUNT(*) returns the number of rows that satisfy the condition in the WHERE clause.

COUNT(expr)

returns the number of non-null values that are in the column identified by expr.

COUNT(DISTINCT expr)

 returns the number of unique, non-null values that are in the column identified by expr.

 

Syntax

SELECT COUNT(aggregate_expression)
FROM tables
[WHERE conditions];

 

OR

 

SELECT expression1, expression2, ... expression_n,
       COUNT(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

 

Parameters or Arguments

expression1, expression2, ... expression_n

Expressions that are not encapsulated within the COUNT function and must be included in the GROUP BY clause at the end of the SQL statement.

aggregate_expression

This is the column or expression whose non-null values will be counted.

Tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions

Optional. These are conditions that must be met for the records to be selected.

 

Only includes NOT NULL Values

Not everyone realizes this, but the COUNT function will only include the records in the count where the value of expression in COUNT(expression) is NOT NULL. When expression contains a NULL value, it is not included in the COUNT calculations.

 

With Single Field

SELECT COUNT(*) AS "Number of employees"
FROM employees
WHERE salary > 75000;

Using DISTINCT

SELECT COUNT(DISTINCT department) AS "Unique departments"
FROM employees
WHERE salary > 55000;

Using GROUP BY

SELECT department, COUNT(*) AS "Number of employees"
FROM employees
WHERE state = 'CA'
GROUP BY department;

Because you have listed one column in your SELECT statement that is not encapsulated in the COUNT function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

 

使用DISTINCT 的方法COUNT函数和NVL函数的区别:

NVL

SELECT DISTINCT NVL(emp_name, 'AAA')
FROM employees;

COUNT

SELECT COUNT(DISTINCT department) AS "Unique departments"
FROM employees
WHERE salary > 55000;

posted @ 2017-07-04 09:37  寻香径  阅读(334)  评论(0编辑  收藏  举报