多列SQL的总和

时间:2015-06-16 09:46:17

标签: sql

我的学生标记数据设置如下

RegNo Subj1 Mark1 Subj2 Mark2 Subj3 Mark3 Subj4 Mark4

其中Subj是主题名称和给定的标记。

数据是这样的,相同的主题可以在不同学生的任何列中。例如。 Student1可能选择Eng作为Subj1,而Student2可能选择Subj2。

现在我需要每个科目的平均值。我怎么找?

2 个答案:

答案 0 :(得分:8)

您应该修复数据结构。通常,当您的列包含相同的数据并且仅在末尾用数字区分时,您的结构就会很糟糕。你想要一个看起来像这样的表:

Regno Subj Mark

每位学生一行subj。这称为联结表,是标准化数据的过程的一部分。

您可以动态创建此查询,但您应该真正修复数据结构:

select subj, avg(mark)
from ((select regno, subj1 as subj, mark1 as mark from studentmark) union all
      (select regno, subj2 as subj, mark2 as mark from studentmark) union all
      (select regno, subj3 as subj, mark3 as mark from studentmark) union all
      (select regno, subj4 as subj, mark4 as mark from studentmark)
     ) sm
group by sub;

SQL Fiddle中的示例。

答案 1 :(得分:1)

您可以计算四个列中每个列中四个主题的UNION个。例如:

SELECT RegNo, Subj1 as Subj, Mark1 as Mark from NormalizeMePlease where Subj1='SQL basics'
UNION
SELECT RegNo, Subj2 as Subj, Mark2 as Mark from NormalizeMePlease where Subj2='SQL basics'
UNION
SELECT RegNo, Subj3 as Subj, Mark3 as Mark from NormalizeMePlease where Subj3='SQL basics'
UNION
SELECT RegNo, Subj4 as Subj, Mark4 as Mark from NormalizeMePlease where Subj4='SQL basics'

为方便起见,它可以变成一个视图。从结构合理的数据中选择平均值或其他任何内容都应该很容易。