我在表格中有这样的数据:
================================
class | name | study | average
================================
1 alfa c# 70
1 beta c# 70
2 carlie c# 80
2 delta c# 80
1 alfa php 80
1 beta php 90
2 carlie php 70
2 delta php 80
我想要这样的结果:
===============================
study | class | avg class
| 1 | 2 |
===============================
c# 70 80 75
php 85 75 80
那么如何在mysql中进行查询以获得这些结果呢?
请帮助我,我已多次尝试但未成功
由于
答案 0 :(得分:1)
这应该对你有用,但是你必须添加一个新的"类"每个数字类号的行。
SELECT study,
(SELECT AVG(average) FROM test t WHERE class='1' AND t.study = test.study) as 'class 1',
(SELECT AVG(average) FROM test t WHERE class='2' AND t.study = test.study) as 'class 2',
AVG(average)
FROM test
GROUP BY study
答案 1 :(得分:0)
试试这个:
SELECT
study,
AVG
(
CASE
WHEN class = 1 THEN average
ELSE NULL
END
) class_1_average,
AVG
(
CASE
WHEN class = 2 THEN average
ELSE NULL
END
) class_2_average,
AVG(average) avg_class
FROM mytable
GROUP BY study;