聚合函数:用于汇总的函数
COUNT:计数
SUM
AVG
MIN
MAX
3.1计算全部行数:
postgres=# SELECT COUNT(*)
postgres-# FROM Product;
count
-------
8
(1 行记录)
3.2COUNT某列不计入NULL值,COUNT(*)会计入
postgres=# SELECT COUNT(purchase_price)
postgres-# FROM Product;
count
-------
6
(1 行记录)
3.4SUM求某列的合计值
postgres=# SELECT SUM(sale_price)
postgres-# FROM Product;
sum
-------
16780
(1 行记录)
3.9MIN和MAX原则上适用于所有数据类型:
postgres=# SELECT MIN(regist_date)
postgres-# FROM Product;
min
------------
2008-04-28
(1 行记录)
3.10计算去除重复数据后的行数:
postgres=# SELECT COUNT(DISTINCT product_type)
postgres-# FROM Product
postgres-# ;
count
-------
3
(1 行记录)
3.12 SUM函数使用DISTINCT
postgres=# SELECT SUM(sale_price),SUM(DISTINCT sale_price)
postgres-# FROM Product;
sum | sum
-------+-------
16780 | 16280
(1 行记录)
GROUP BY分组语句
GROUP指定的句子叫聚合键
3.13按照商品种类分组计数
postgres=# SELECT product_type,COUNT(*)
postgres-# FROM Product
postgres-# GROUP BY product_type;
product_type | count
--------------+-------
衣服 | 2
办公用品 | 2
厨房用具 | 4
(3 行记录)
3.15 GROUP BY 和WHERE 连用
postgres=# SELECT purchase_price,COUNT(*)
postgres-# FROM Product
postgres-# WHERE product_type='衣服'
postgres-# GROUP BY purchase_price;
purchase_price | count
----------------+-------
500 | 1
2800 | 1
(2 行记录)
GROUP的使用注意事项:
1.SELECT语句后面不可以写聚合键以外的列名
2.先执行GROUP,后执行SELECT,所以GROUP语句后面不可以写别名
3.GROUP的结果是无序的。
4.WHERE 语句不能使用聚合函数
HAVING子句:
3.20对分组后的结果选取数据行数为2的组。
postgres=# SELECT product_type,COUNT(*)
postgres-# FROM Product
postgres-# GROUP BY product_type
postgres-# HAVING COUNT(*)=2;
product_type | count
--------------+-------
衣服 | 2
办公用品 | 2