使用group by从sql中的两个表所需的数据

时间:2017-07-20 13:59:10

标签: mysql

The two existing tables.

表1显示了受试者及其组成部分。 表2显示了每个受试者及其相应成分的标记。 表2通过其主键与表1相关。

This image includes the expected output data required from table 1 and table 2

第二张图片显示了预期的输出,其中每一行显示该特定学生特定科目的组成部分的数量,以及学生在该科目中获得的分数总和(该科目中所有成分的分数总和)

我尝试过多次分组声明,但仍无法达到所需的输出。 如果提供有效的解决方案,那将是非常有帮助的。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

  

查询-1:

SELECT sub_id, COUNT(component_id) t1_component_count
FROM table1
GROUP BY sub_id;

Output:
+--------+--------------------+
| sub_id | t1_component_count |
+--------+--------------------+
| s1     |                  3 |
| s2     |                  3 |
| s3     |                  1 |
| s4     |                  1 |
+--------+--------------------+
  

查询-2:

SELECT t2.stu_id, t1.sub_id, t3.comp_cnt AS t1_component_count,
 count(t1.component_id) AS t2_component_count, sum(t2.stu_marks) total_marks
FROM table2 t2 INNER JOIN table1 t1 ON t2.t1_id = t1.t1_id
  INNER JOIN
   (SELECT sub_id, COUNT(component_id) comp_cnt FROM table1 GROUP BY sub_id)
    AS t3 ON t1.sub_id = t3.sub_id
 GROUP BY t2.stu_id, t1.sub_id;

Output:
+--------+--------+--------------------+--------------------+-------------+
| stu_id | sub_id | t1_component_count | t2_component_count | total_marks |
+--------+--------+--------------------+--------------------+-------------+
| stu1   | s1     |                  3 |                  3 |         100 |
| stu1   | s2     |                  3 |                  2 |         130 |
| stu2   | s3     |                  1 |                  1 |          50 |
| stu3   | s2     |                  3 |                  1 |          30 |
| stu4   | s1     |                  3 |                  1 |          90 |
+--------+--------+--------------------+--------------------+-------------+