MySQL选择聚合函数

时间:2015-03-07 08:57:30

标签: mysql

我有这个简单的查询:

SELECT 
      score,subject_name 
 FROM exams_scores,subjects 
WHERE (admission_no = 2771) AND(subjects.subject_code = exams_scores.subject_code)

这给了我:所有5条记录都符合预期。 如果我这样做:

SELECT 
      score,
      subject_name,
      SUM (score) as TOTAL 
FROM exams_scores,subjects
WHERE (admission_no = 2771) AND (subjects.subject_code = exams_scores.subject_code)

我只得到第一个分数。如果想获得所有分数加上他们的总和,我应该使用什么。

示例数据

admission_no       subject     score
1000               Engligh      80
1000               Math         90
1000               Physics      70
2000               English      45
2000               Math         80
2000               Physics      90

我试图获得特定录取的所有标记_no加上总数 所以我期待:

admission_no:1000,

得分:80,90,70

总数:240

2 个答案:

答案 0 :(得分:0)

您的第二个查询会将所有行聚合为一个总和。这应该是它应该做的。 为了保留行,一种方法是在select语句中添加创建总和,如下所示:

SELECT 
   score,
   subject_name,
   (SELECT SUM (score) FROM exams_scores,subjects WHERE (admission_no = 2771) AND (subjects.subject_code = exams_scores.subject_code)) AS sum
FROM exams_scores,subjects 
WHERE (admission_no = 2771) AND(subjects.subject_code = exams_scores.subject_code)

像这样,总和会附加到每一行。


编辑:为了添加总行,union语句可以完成这项工作:

SELECT 
   score,
   subject_name,
   (SELECT SUM (score) FROM exams_scores,subjects WHERE (admission_no = 2771) AND (subjects.subject_code = exams_scores.subject_code)) AS sum
FROM exams_scores,subjects 
WHERE (admission_no = 2771) AND(subjects.subject_code = exams_scores.subject_code)

UNION

SELECT (0, 'Total', (SELECT SUM(... ... ...))

这应该这样做,但我没有详细测试过。这只是最后一行,而不是每组一行。

使用union,您始终需要相同的数字,名称和列类型。还有一点可能是最好离开SQL并使用PHP结构来添加标题,格式化等。

答案 1 :(得分:0)

听起来你正在寻找一个可以用工会做的卷起来。

SELECT score,subject_name 
 FROM  exams_scores,subjects 
WHERE  (admission_no = 2771) AND(subjects.subject_code = exams_scores.subject_code)
UNION ALL
SELECT sum(score), 'Total'
 FROM  exams_scores
WHERE  (admission_no = 2771)