2

我有以下表格布局

表一

Teacher Students
Mohan pankaj
Mohan sudeepa
Mohan sujitra
Mohan Sumit

表b(第一学期分数)

Pankaj Maths 50
Pankaj English 40
Pankaj Physics 60
Sudeepa Chemisty 40
Sujitra Physic 10
Sujitra English 40
Sujitra Hindi 70

表c(第2学期分数)

Pankaj Chemistry 50
Pankaj English 40
Pankaj Physics 60
Sudeepa Science 40
Sujitra Physic 10
Sujitra Maths 40
Sujitra Hindi 70

我想要输出为: -

hindi 140.00
maths 40.00
physics 10.00
science 40.00
chemistry 40.00
english 40.00
physics 10.00

我写了查询

select subject,sum(marks) from sample.b where
student in ( select student from sample.a where teacher='mohan')
group by subject

union all
select subject,sum(marks) from sample.c
where student in ( select student from sample.test where teacher='mohan')
group by subject

我得到的结果是

hindi 70.00
maths 40.00
physics 10.00
science 40.00
chemistry 40.00
english 40.00
hindi 70.00
physics 10.00

*问题* Same subjects marks are not adding up ..

4

2 回答 2

0

更新您的查询可能看起来像

SELECT s.subject, s1.marks sem1_marks, s2.marks sem2_marks
FROM
(
  SELECT b.subject 
    FROM b JOIN a 
      ON b.student = a.students
   WHERE a.teacher = 'Mohan'
   UNION 
  SELECT c.subject 
    FROM c JOIN a 
      ON c.student = a.students
   WHERE a.teacher = 'Mohan'
) s 
LEFT JOIN
(
  SELECT b.subject, SUM(b.marks) marks
    FROM b JOIN a 
      ON b.student = a.students
   WHERE a.teacher = 'Mohan'
   GROUP BY b.subject
) s1 ON s.subject = s1.subject 
LEFT JOIN
(
  SELECT c.subject, SUM(c.marks) marks
    FROM c JOIN a 
      ON c.student = a.students
   WHERE a.teacher = 'Mohan'
   GROUP BY c.subject
) s2 ON s.subject = s2.subject

输出:

| 主题 | SEM1_MARKS | SEM2_MARKS |
--------------------------------------
| 化学 | 40 | 50 |
| 英语 | 80 | 40 |
| 印地语 | 70 | 70 |
| 数学 | 50 | 40 |
| 物理学 | 70 | 70 |
| 科学 | (空) | 40 |

这是SQLFiddle演示(同样是 SQL Server,但应该在 DB2 中工作)。

原始问题的原始答案: 您需要先UNION ALL在内部选择中处理两个数据集(聚合或不聚合),然后在外部选择中应用SUM()聚合GROUP BY

SELECT subject, SUM(marks) marks
FROM
(
  SELECT student, subject, marks 
    FROM b JOIN a 
      ON b.student = a.students
   WHERE a.teacher = 'Mohan'
   UNION ALL
  SELECT student, subject, marks 
    FROM c JOIN a 
      ON c.student = a.students
   WHERE a.teacher = 'Mohan'
) q
 GROUP BY subject

输出:

| 主题 | 标记 |
---------------------
| 化学 | 90 |
| 英语 | 120 |
| 印地语 | 140 |
| 数学 | 90 |
| 物理学 | 140 |
| 科学 | 40 |

这是SQLFiddle演示(SQL Server)。但我相信它应该在 DB2 中同样工作。

于 2013-06-28T06:20:00.113 回答
0

This should give you what you've asked for, by segregating the grades into separate columns.

Select subject, sum(s1mark) sem1tot, sum(s2mark) sem2tot
From ( select subject, mark as s1mark, 0 as s2mark
         From b join a  on a.student=b.student and a.teacher='Mohan'
       UNION
       select subject, 0 as s1mark, mark as s2mark
         From b join a  on a.student=b.student and a.teacher='Mohan'
     )
group by subject
order by subject
于 2013-06-29T01:58:21.930 回答