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;

转载于:https://www.cnblogs.com/thescentedpath/p/COUNT.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值