标签:
为了数据的转换和处理方便,SQL提供了函数用来处理文本字符串、进行算术操作、处理日期和时间值、返回DBMS所使用的特殊信息。
文本处理函数常用的大小写转换、清除空格、统计长度、返回SOUNDEX同音字符串等。
大写转换使用UPPER()函数:
mysql> select UPPER(cust_name) FROM Customers;
+------------------+
| UPPER(cust_name) |
+------------------+
| VILLAGE TOYS |
| KIDS PLACE |
| FUN4ALL |
| FUN4ALL |
| THE TOY STORE |
+------------------+
5 rows in set (0.00 sec)
小写转换使用LOWER()函数:
select LOWER(cust_name) FROM Customers;
SOUNDEX用于返回同音字符串,比如在Customers表中cust_contact列的名字为Michelle Green,如果输入错误Michael Green将会查不到结果:
mysql> SELECT cust_name,cust_contact FROM Customers where cust_contact = ‘Michael Green‘;
Empty set (0.00 sec)
使用SOUNDEX函数后:
mysql> SELECT cust_name,cust_contact FROM Customers where SOUNDEX(cust_contact) =SOUNDEX(‘Michael Green‘);
+------------+----------------+
| cust_name | cust_contact |
+------------+----------------+
| Kids Place | Michelle Green |
+------------+----------------+
1 row in set (0.00 sec)
提取日期年份(说明:不同的DBMS对日期处理函数的支持不一样,这里使用的是mysql):
查询2010年的订单:
mysql> select * from Orders WHERE YEAR(ORDER_DATE)=2010;
+-----------+---------------------+------------+
| order_num | order_date | cust_id |
+-----------+---------------------+------------+
| 20010 | 2010-05-27 00:00:00 | 1000000010 |
| 20011 | 2010-09-27 00:00:00 | 1000000011 |
| 20013 | 2010-11-12 00:00:00 | 1000000013 |
| 20015 | 2010-04-15 00:00:00 | 1000000015 |
+-----------+---------------------+------------+
4 rows in set (0.01 sec)
数值处理函数可以用户代数、三角或几何运算。
函数 | 说明 |
---|---|
ABS() | 返回一个数的绝对值 |
COS() | 返回一个角度的余弦值 |
EXP() | 返回一个数的指数值 |
PI() | 返回圆周率 |
SIN() | 返回一个角度的正弦值 |
SORT() | 返回一个数的平方根 |
TAN() | 返回一个角度的正切 |
聚集函数可以用来求和、求平均值、求最大最小值、统计行数、求标准差。
以Products表的pord_price列为例:
mysql> select SUM(prod_price) AS SUM FROM Products;
+-------+
| SUM |
+-------+
| 61.41 |
+-------+
1 row in set (0.00 sec)
mysql> select AVG(prod_price) AS AVG FROM Products;
+----------+
| AVG |
+----------+
| 6.823333 |
+----------+
1 row in set (0.00 sec)
mysql> select MAX(prod_price) AS MAX_PRICE FROM Products;
+-----------+
| MAX_PRICE |
+-----------+
| 11.99 |
+-----------+
1 row in set (0.00 sec)
mysql> select MIN(prod_price) AS MIN_PRICE FROM Products;
+-----------+
| MIN_PRICE |
+-----------+
| 3.49 |
+-----------+
1 row in set (0.01 sec)
mysql> select COUNT(*) AS TOTAL FROM PRODUCTS;
+-------+
| TOTAL |
+-------+
| 9 |
+-------+
1 row in set (0.00 sec)
mysql> select STD(prod_price) AS STD FROM PRODUCTS;
+----------+
| STD |
+----------+
| 3.036811 |
+----------+
1 row in set (0.00 sec)
select语句可以根据需求同时使用多个聚集函数:
mysql> select COUNT(*) AS 总个数,Max(prod_price) AS 最高价格 from Products;
+-----------+--------------+
| 总个数 | 最高价格 |
+-----------+--------------+
| 9 | 11.99 |
+-----------+--------------+
1 row in set (0.00 sec)
标签:
原文地址:http://blog.csdn.net/napoay/article/details/50818475