无法让SUM在mysql中工作

时间:2011-08-10 14:22:42

标签: mysql sum

我需要这个

  GROUP_ID     TOTALSUM       
     1          67,40000000
     2          56,5454

使用此查询

 select 
     exam.id, exam.ponderation / totalponderation *  avg(scores.result) as totalsum
 from 
    scores, exam,
    (SELECT SUM(ponderation) AS totalponderation
     FROM exam) AS sumponderation
 where 
     exam.group_id in (91, 93) and exam.id = scores.exam_id
 group by 
     exam.name

我尝试了很多查询,但没有任何效果。

查询#1(不起作用)(query error)

select sum(exam.ponderation / totalponderation *  avg(scores.result)) as totalsum

查询#2(不起作用)(它返回251 as total

 select sum( exam.ponderation / totalponderation *  avgscores )
 from scores, exam,
      (SELECT SUM(ponderation) AS totalponderation
       FROM exam) AS sumponderation,
      (SELECT avg(scores.result) AS avgscores
       FROM scores, exam
       where exam.group_id in(91,93)  and exam.id = scores.exam_id) AS avgponderation

所以...我可以做一下我的专栏吗?

修改

我的考试表

  

ID ---- -----名----思考--- GROUP_ID ---- subject_id日期戳
  1 ------ test1 ---------- 150 ---------- 4 ------------ 4 ------- ------ 2011-11-11
   2 ------ test2 ---------- 20 ---------- 4 ------------ 4 ------- ------ 2011-11-11
  3 ------- TEST3 --------- --------- 20 3 -------------- ------ 4 ------- 2011-11-11

我的分数表

  

id ---- exam_id ----- user_id ---- subject_id结果------------- date ------ order
  1 ------ 1 ------------ 5 ------------- 4 ------------ 80-- ----------- 2011-11-11 ------- 1
   2 ------ 2 ------------ 25 ------------- 4 ------------ 30-- ----------- 2011-11-11 ------ 0
   3 ------ 1 ------------ 5 ------------- 4 ------------ 61-- ----------- 2011-11-11 ------- 1
   4 ------ 2 ------------ 25 ------------- 4 ------------ 80-- ----------- 2011-11-11 ------ 0

编辑:我需要分组BY group_id

  GROUP_ID     TOTALSUM       
         1          67,40000000
         2          56,5454

THX

1 个答案:

答案 0 :(得分:2)

在使用之前计算另一个内联视图中的avgscores可能会解决您的问题

SELECT 
e.group_id,
   SUM(e.ponderation /  totalponderation *  avgscores)  TOTAL_sum

FROM 
    exam e

    INNER JOIN (SELECT exam_id, avg(scores.result) avgscores 
         FROM scores
      GROUP BY exam_id) a
    ON e.id = a.exam_id,
    (SELECT SUM(ponderation) AS totalponderation
      FROM exam) AS sumponderation
Group by 
   e.group_id