排名
数值相同的排名相同且排名连续
SELECT prod_price, (SELECT COUNT(DISTINCT prod_price) FROM products WHERE prod_price>=a.prod_price ) AS rank FROM products AS a ORDER BY rank ;
5 字符串处理
字符串替换
UPDATE data1 SET city=REPLACE(city,'SH','shanghai'); SELECT city FROM data1;
按位置字符串截取
字符串截取可用于数据分列
MySQL 字符串截取函数:left(), right(), substring(), substring_index()
SELECT left('example.com', 3);
从字符串的第 4 个字符位置开始取,直到结束
SELECT substring('example.com', 4);
从字符串的第 4 个字符位置开始取,只取 2 个字符
SELECT substring('example.com', 4, 2);
按关键字截取字符串
取第一个分隔符之前的所有字符,结果是www
SELECT substring_index('www.google.com','.',1);
取倒数第二个分隔符之后的所有字符,结果是google.com;
SELECT substring_index('www.google.com','.',-2);
6 筛选
通过操作符实现高级筛选
使用 AND OR IN NOT 等操作符实现高级筛选过滤
SELECT prod_name,prod_price FROM Products WHERE vend_id IN('DLL01','BRS01'); SELECT prod_name FROM Products WHERE NOT vend_id='DLL01';
通配符筛选
常用通配符有% _ [] ^
SELECT * from customers WHERE country LIKE "CH%";
7 表联结
SQL表连接可以实现类似于Excel中的Vlookup函数的功能
SELECT vend_id,prod_name,prod_price FROM Vendors INNER JOIN Products ON Vendors.vend_id=Products.vend_id; SELECT prod_name,vend_name,prod_price,quantity FROM OderItems,Products,Vendors WHERE Products.vend_id=Vendors.vend_id AND OrderItems.prod_id=Products.prod_id AND order_num=20007;
自联结 在一条SELECT语句中多次使用相同的表
SELECT c1.cust_od,c1.cust_name,c1.cust_contact FROM Customers as c1,Customers as c2 WHERE c1.cust_name=c2.cust_name AND c2.cust_contact='Jim Jones';
8 数据透视
数据分组可以实现Excel中数据透视表的功能
数据分组
group by 用于数据分组 having 用于分组后数据的过滤
SELECT order_num,COUNT(*) as items FROM OrderItems GROUP BY order_num HAVING COUNT(*)>=3;
交叉表
通过CASE WHEN函数实现
SELECT data1.city, CASE WHEN colour = "A" THEN price END AS A, CASE WHEN colour = "B" THEN price END AS B, CASE WHEN colour = "C" THEN price END AS C, CASE WHEN colour = "F" THEN price END AS F FROM data1
注:以上代码在MySQL数据库中执行