MySQL 分組百分比是指在使用GROUP BY進行分組查詢的基礎上,統計每個組所占總數的百分比。
以下是一個演示MySQL分組百分比的示例,假設有如下表tb_score:
CREATE TABLE tb_score ( id INT PRIMARY KEY, name VARCHAR(20), subject VARCHAR(20), score INT );
向該表中插入數據:
INSERT INTO tb_score VALUES (1, '張三', '語文', 90); INSERT INTO tb_score VALUES (2, '張三', '數學', 80); INSERT INTO tb_score VALUES (3, '李四', '語文', 70); INSERT INTO tb_score VALUES (4, '李四', '數學', 85); INSERT INTO tb_score VALUES (5, '王五', '語文', 95);
現在要統計每個學生的語文成績和數學成績之和,以及每個科目所占成績總和的百分比。
SELECT name, SUM(IF(subject='語文',score,0)) AS ChineseScore, SUM(IF(subject='數學',score,0)) AS MathScore, ROUND(SUM(IF(subject='語文',score,0))/(SELECT SUM(score) FROM tb_score)*100,2) AS ChinesePercent, ROUND(SUM(IF(subject='數學',score,0))/(SELECT SUM(score) FROM tb_score)*100,2) AS MathPercent FROM tb_score GROUP BY name;
輸出結果:
+------+--------------+----------+---------------+------------+ | name | ChineseScore | MathScore | ChinesePercent | MathPercent | +------+--------------+----------+---------------+------------+ | 張三 | 90 | 80 | 40.91 | 36.36 | | 李四 | 70 | 85 | 31.82 | 38.64 | | 王五 | 95 | 0 | 43.18 | 0 | +------+--------------+----------+---------------+------------+
通過以上查詢,可以看到每個學生的語文成績和數學成績之和,以及每個科目所占成績總和的百分比。
上一篇mysql 分行
下一篇2.MySQL有哪些版本