提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
MySQL 进阶语句
- 算排名
- 算中位数
- 算累积总计
- 算总合百分比
- 算累积总合百分比
use zs;
CREATE TABLE ikun (Name char(10),Sales int(5));
INSERT INTO ikun VALUES ('cx',10);
INSERT INTO ikun VALUES ('ls',15);
INSERT INTO ikun VALUES ('zs',20);
INSERT INTO ikun VALUES ('ww',40);
INSERT INTO ikun VALUES ('myh',50);
INSERT INTO ikun VALUES ('xjz',20);
INSERT INTO ikun VALUES ('ztm',30);
ikun 表格
+----------+---------+
| Name | Sales |
|----------+---------|
| cx | 10 |
| ls | 15 |
| zs | 20 |
| ww | 40 |
| myh | 50 |
| xjz | 20 |
| ztm | 30 |
+----------+---------+
算排名
表格自我连结 (Self Join),然后将结果依序列出,算出每一行之前 (包含那一行本身) 有多少行数
SELECT A1.Name, A1.Sales, COUNT(A2.Sales) Rank FROM ikun A1, ikun A2
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name = A2.Name)
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;
算中位数
SELECT Name, Sales Middle FROM (SELECT A1.Name,A1.Sales,COUNT(A2.Sales) Rank FROM ikun A1,ikun A2
WHERE A1.Sales < A2.Sales OR (A1.Sales = A2.Sales AND A1.Name >= A2.Name)
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC) A3
WHERE A3.Rank = (SELECT (COUNT(*)+1) DIV 2 FROM ikun);
#每个派生表必须有自己的别名,所以别名 A3 必须要有
#DIV 是在 MySQL 中算出商的方式
算累积总计
表格自我连结 (Self Join),然后将结果依序列出,算出每一行之前 (包含那一行本身) 的总合
SELECT A1.Name, A1.Sales, SUM(A2.Sales) Sum_Total, COUNT(A2.Sales) Rank FROM ikun A1, ikun A2
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name = A2.Name)
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;
算总合百分比
SELECT A1.Name, A1.Sales, A1.Sales/(SELECT SUM(Sales) FROM ikun) Per_Total, COUNT(A2.Sales) Rank
FROM ikun A1, ikun A2
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name = A2.Name)
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;
#SELECT SUM(Sales) FROM ikun 这一段子查询是用来算出总合
#总合算出后,我们就能够将每一行一一除以总合来求出每一行的总合百分比
SELECT A1.Name, A1.Sales, ROUND(A1.Sales/(SELECT SUM(Sales) FROM ikun)*100,2) || '%' Percent,
COUNT(A2.Sales) Rank FROM ikun A1, ikun A2 WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales AND A1.Name >= A2.Name) GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;
算累积总合百分比
SELECT A1.Name, A1.Sales, SUM(A2.Sales)/(SELECT SUM(Sales) FROM ikun) Per_Total, COUNT(A2.Sales) Rank
FROM ikun A1, ikun A2
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales and A1.Name = A2.Name)
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;
#用累积总计 SUM(a2.Sales) 除以总合来求出每一行的累积总合百分比
SELECT A1.Name, A1.Sales, ROUND(SUM(A2.Sales)/(SELECT SUM(Sales) FROM ikun)*100,2) || '%' Per_Total, COUNT(A2.Sales) Rank FROM ikun A1, ikun A2
WHERE A1.Sales < A2.Sales OR (A1.Sales=A2.Sales and A1.Name = A2.Name)
GROUP BY A1.Name, A1.Sales ORDER BY A1.Sales DESC;