我需要帮助为MySQL数据库生成SQL。
我有两张桌子:
学生表:
+------------+---------+-----------------+ | id | name |area_of_study_id | +------------+---------+-----------------+ | 1 | AAA | 1 | | 2 | BBB | 2 | | 3 | CCC | 1 | | 4 | DDD | 3 | | 5 | EEE | 4 | | 6 | FFF | 1 | | 7 | GGG | 2 | | 8 | III | 1 | +------------+---------+-----------------+
student_subjects表:
+------------+-------------------+------------------+ | id | student_id | subject_id | | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 1 | 3 | | 4 | 1 | 2 | | 5 | 3 | 1 | | 6 | 6 | 1 | | 7 | 7 | 3 | | 8 | 4 | 6 | +------------+-------------------+------------------+
我需要根据subject's area of study
找出students area of study
。从学生表上方您可以看到学生可以自由选择area of study
。有时,他们可以选择与他们的学习领域无关的科目。因此,在这种情况下,我们需要根据已经拍摄主题的area of study
计算subject
student percentages
。
部分输出:
+------------+-------------------+-----------------------------------+ |Total_students | subject_id |area_of_study_id | percentage | +------------+-------------------+-----------------+-----------------+ | 3 | 1 | 1 | 75 | | 1 | 1 | 2 | 25 | | 1 | 3 | 1 | 50 | | 1 | 3 | 2 | 50 | | 1 | 2 | 1 | 100 | | 1 | 6 | 3 | 100 | +------------+-------------------+-----------------+-----------------+
从上面的部分输出中,我们可以看到,3名学生选择一个学科(即subject_id = 1)具有学习领域1
而一名学生来自不同的学习领域(即2)。因此,我们可以说subject_id =1
来自area of study = 1
。
如果受试者的百分比为50%。我们可以选择两者之间的任何研究领域,无论哪一个。
预期输出:
+------------+-------------------+-----------------------------------+ |Total_students | subject_id |area_of_study_id | percentage | +------------+-------------------+-----------------+-----------------+ | 3 | 1 | 1 | 75 | | 1 | 3 | 1 | 50 | | 1 | 2 | 1 | 100 | | 1 | 6 | 3 | 100 | +------------+-------------------+-----------------+-----------------+
答案 0 :(得分:2)
以这种方式试试
SELECT subject_id, area_of_study_id, total_students, percentage
FROM
(
SELECT p.subject_id, p.area_of_study_id, p.total_students,
p.total_students / t.total_students * 100 percentage
FROM
(
SELECT COUNT(*) total_students, ss.subject_id, s.area_of_study_id
FROM students s JOIN student_subjects ss
ON s.id = ss.student_id
GROUP BY ss.subject_id, s.area_of_study_id
) p JOIN
(
SELECT ss.subject_id, COUNT(*) total_students
FROM students s JOIN student_subjects ss
ON s.id = ss.student_id
GROUP BY ss.subject_id
) t ON p.subject_id = t.subject_id
ORDER BY percentage DESC
) q
GROUP BY subject_id;
输出:
| SUBJECT_ID | AREA_OF_STUDY_ID | TOTAL_STUDENTS | PERCENTAGE | |------------|------------------|----------------|------------| | 1 | 1 | 3 | 75 | | 2 | 1 | 1 | 100 | | 3 | 1 | 1 | 50 | | 6 | 3 | 1 | 100 |
这是 SQLFiddle 演示