基本用法和类型:
SELECT function(列) FROM 表
在 SQL 中,基本的函数类型和种类有若干种。函数的基本类型是:Aggregate 函数 和 Scalar 函数
Aggregate 函数的操作面向一系列的值,并返回一个单一的值。Scalar 函数的操作面向某个单一的值,并返回基于输入值的一个单一的值。
Aggregate函数
1、AVG函数 返回平均值
SELECT AVG(OrderPrice) AS OrderAverage FROM Orders
SELECT Customer FROM Orders
WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders) 本质就是筛选price大于平均值的
2、COUNT 返回匹配指定条件的行数
SELECT COUNT(DISTINCT column_name) FROM table_name
SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Carter' 客户Carter的订单数
3、FIRST / LAST / MAX / MIN
SELECT FIRST(column_name) FROM table_name
SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders 同理MIN
4、SUM / GROUP BY
SELECT SUM(OrderPrice) AS OrderTotal FROM Orders
合计函数 (比如 SUM) 常常需要添加 GROUP BY 语句。
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer 希望查找每个客户的总金额(总订单)需要对客户进行分组
5、HAVING WHERE 无法与合计函数一起使用
查找订单总金额少于 2000 的客户:
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
查找客户 "Bush" 或 "Adams" 拥有超过 1500 的订单总金额:
SELECT Customer,SUM(OrderPrice) FROM Orders
WHERE Customer='Bush' OR Customer='Adams'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500
Scalar函数
1、UCASE LCASE
UCASE 函数把字段的值转换为大写。LCASE 函数把字段的值转换为小写。
2、MID 从文本字段中提取字符
SELECT MID(column_name,start[,length]) FROM table_name
SELECT MID(City,1,3) as SmallCity FROM Persons
"City" 列中每一行都提取前 3 个字符
3、LEN 返回值的长度
4、FORMAT 格式化字段显示
SELECT FORMAT(column_name,format) FROM table_name
SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate FROM Products
5、ROUND 把数值字段舍入为指定的小数位数
SELECT ROUND(column_name,decimals) FROM table_name
demicals:规定要返回的小数位数 SQL基本的整理结束,之后会更基于MySQL的实际应用方面的笔记
TO BE CONT'D.
网友评论