创建计算字段
拼接字段
将多个列值联结构成单个值。
SELECT Concat(vend_name, ' (', vend_country, ')')
FROM vendors
ORDER BY vend_name;
RTrim():去掉串右边的空格
LTrim():去掉串左边的空格
Trim():去掉串左右两边的空格
SELECT Concat(RTrim(vend_name), ' (', RTrim(vend_country), ')')
FROM vendors
ORDER BY vend_name;
使用别名
AS
SELECT Concat(RTrim(vend_name), ' (', RTrim(vend_country), ')') AS vend_title
FROM vendors
ORDER BY vend_name;
执行算术计算
SELECT prod_id, quantity, item_price, quantity * item_price AS expanded_price
FROM orderitems
WHERE order_num = 2005;
算术运算符
+、-、*、/
使用数据处理函数
文本处理函数
Soundex 考虑类似的发音字符和音节
SELECT cust_name, cust_contact
FROM customers
WHERE Soundex(cust_contact) = Soundex('Y. Lie');
日期处理函数
日期,尽量使用Date()
SELECT cust_id, order_num
FROM orders
WHERE Date(order_date) = '2005-09-1';
检测出9月所有的订单
SELECT cust_id, order_num
FROM orders
WHERE Date(order_date) BETWEEN '2005.9.1' AND '2005.09.30';
另一种方法
SELECT cust_id, order_num
FROM orders
WHERE Year(order_date) = 2005 AND Month(order_date) = 9;
数值处理函数
汇集数据
聚集函数
例
SELECT COUNT(*) AS num_cust
FROM customers;
COUNT、AVG、MAX、MIN、SUM函数忽略列值为NULL的行。COUNT(*)不忽略
聚集不同的值
取平均值,只考虑不同的价格
SELECT AVG(DISTINCT prod_price) AS avg_price
FROM products
WHERE vend_id = 1003;
组合聚集函数
SELECT COUNT(*) AS num_items, MIN(prod_pice) AS price_min
FROM products;
分组数据
数据分组操作
返回每个供应商提供的产品数目。
SELECT vend_id, COUNT(*) AS num_prods
FROM products
GROUP BY vend_id;
特别注意
(1)GROUP BY子句可以包含任意数目的列
(2)GROUP BY子句中列出的每个列都必须是检索列或者有效表达式(但不能是聚集函数)。SELECT中使用表达式,则GROUP BY子句中指定相同的表达式,不能使用别名。
(3)GROUP BY 子句必须在WHERE子句之后,ORDER BY子句之前。
过滤分组—HAVING
SELECT cust_id, COUNT(*) AS orders
FROM orders
GROUP BY cust_id
HAVING COUNT(*) >= 2;
COUNT(*) >= 2 表示cust_id大于等于2的那些分组
HAVING 和 WHERE 区别
WHERE 在数据分组前进行过滤,HAVING在数据分组后进行过滤。
列出具有2个以上、价格大于10的产品的供应商
SELECT vend_id, COUNT(*) AS num_prods
FROM products
WHERE prod_price >= 10
GROUP BY vend_id
HAVING COUNT(*) >= 2;
SELECT子句顺序