数据库(三)

统计——聚合函数(统计函数) 

1、COUNT(*)--总数

select COUNT(*) from chinastates where areacode like '_ _ _ _'--统计chinastates表内地级市的总数(areacode like '_ _ _ _'代表地级市)。

PS:COUNT 后为列名的话,以列计数,那么查询列中为NULL值的则被忽略不予计数。

2、AVG--平均值

select AVG(price) from car where brand in('b001','b002','b003','b004')--求car表中系列代码为'b001','b002','b003','b004'的平均值。

3、SUM--总和

select SUM (price) from car--统计car表中所有价格的总和,()内可以写多列,如:price/ids.

select *,(price*0.9) as 价格 from car--统计价格九折后的价格显示在表最后,列名为价格。

select code 代号,name 名称,brand 系列,Time 上市时间,oil 油耗,powers 功率,Exhaust 排量,price 价格,pic 图片路径 from car--用汉字列名表示英文列名。

4、MAX--最大值

select MAX(price) from car--显示价格最大值。

5、MIN--最小值

select MIN(price) from car--显示价格最小值。

分组 

1、select oil,COUNT(*) from car group by oil order by COUNT(*) desc--按照oil进行分组,显示出oil列和没组的个数并降序排列。

2、select oil,COUNT(*) from car where price>50 group by oil order by COUNT(*) desc--对价格大于50的按照oil进行分组并降序排列。

3、select type,COUNT(*) from fruit group by type having COUNT(*)>1--按照type进行分组,将组内个数大于1的type和个数显示出来。

PS:having是针对统计好的结果进行筛选,所以使用having的前提必须使用group by.

函数 

1、幂函数

SQRT--平方根

2、取近似值函数

① CEILING

ceiling(3.2)--4

② FLOOR

floor(3.2)--3

③ ROUND(索引中ROUND函数T-SQL)

print round(345.987,0)--346.000    0是指保留小数点后几位。

print round(345.876,-1)--350.000    -1是指四舍五入到十位。

print round(345.876,-2)--300.000    -2是指四舍五入到百位。

3、符号函数

ABS--绝对值  可用于两列值相减不管列值是正数还是负数都不受影响。

4、其它函数

RAND--0至1之间的随机数(以时间作为种子),永远不等于1。

原文地址:https://www.cnblogs.com/mxx0426/p/4067720.html