加入两张桌子,找到每个学生的分数总和

时间:2013-11-07 06:15:55

标签: mysql sql database-design

我有两个结果表,一个中期结果表和年度结果表。

中期结果表: enter image description here

年度结果表:

我想加入他们并找到每个学生的每个学生的总分数

找到中期和终结果enter image description here的总分数后

想要的结果表

到目前为止

我的代码:

mysql_query("drop view if exists result_view");
mysql_query("create view result_view as 
           select * from mid_term
            UNION ALL
           select * from annual") or die(mysql_error());

//now find the total marks of students for each subject
mysql_query("select id,student_id,subject_id,result_id,year,sum(mark) as mark
              from result_view ");

但这不起作用,任何帮助或建议PLZ !!!!!! 1

5 个答案:

答案 0 :(得分:0)

我认为id字段在结果中没有多大意义所以我省略了它。

SELECT   Student_id, 
         Subject_id, 
         Result_id, 
         year,
         SUM(mark)
    FROM result_view
GROUP BY Student_id, 
         Subject_id, 
         Result_id,
         year

答案 1 :(得分:0)

您需要GROUP BY:

select id, student_id, subject_id,result_id,year,sum(mark) as TotalMark
from result_view
GROUP BY id, student_id, subject_id, result_id, year

查看我的SqlFiddle

答案 2 :(得分:0)

假设表格的result_id保持不变,请尝试

SELECT m.id,m.student_id,m.subject_id,m.result_id,m.year,(m.mark+a.mark) AS mark
FROM mid_term m, annual a
WHERE m.result_id=a.result_id

答案 3 :(得分:0)

 select t1.id,t1.student_id,t1.subject_id,t1.year,
    t1.result_id,t1.mark+t2.mark as marks from table t1 
    inner join table t2 on t1.id=t2.id 
    order by t1.id

答案 4 :(得分:0)

您可以使用像这样的查询

SELECT
    mt.id,
    mt.student_id,
    mt.subject_id,
    mt.result_id,
    mt.year,
    (mt.mark + ar.mark) marks
FROM mid_term mt
LEFT JOIN annual ar 
ON ar.student_id = mt.student_id
AND ar.result_id = mt.result_id
AND ar.year = mt.year
AND ar.subject_id = mt.subject_id
GROUP BY mt.student_id,mt.subject_id

Fiddle

输出

| ID | STUDENT_ID | SUBJECT_ID |     RESULT_ID | YEAR | MARKS |
|----|------------|------------|---------------|------|-------|
|  1 |      Stud1 |         PH | Stud1/PH/2013 | 2013 |   100 |
|  2 |      Stud1 |         CH | Stud1/CH/2013 | 2013 |    99 |
|  3 |      Stud2 |         PH | Stud2/PH/2013 | 2013 |   100 |
|  4 |      Stud2 |         CH | Stud2/CH/2013 | 2013 |   100 |