在where子句和

时间:2015-07-05 14:01:14

标签: mysql

我需要计算一些数学方程并检查它是否存储在另一个表中的范围内。如下表所示:

+--------------+-------+--------+-------+--------+
| no    | TOTAL | Out Of  |  grad   | point      |
+--------------+-------+--------+-------+--------+
| 1000  | 833   |  1100   |   A     |     12     |
+--------------+-------+--------+-------+--------+

av尝试使用以下

来实现它

查询

SELECT no,sum(score) as TOTAL,(100*count(scores.code)) as "Out Of",
       grad, point 
from scores,gradings 
where (no=1000) and (exam=1) 
and ((sum(score)/(100*count(exams_scores.subject_code))*100) 
  between gradings.range_begin and gradings.range_end)
;

评分表

+---------------------------------------------------+
| id   | range_begin  | range_end |  grad  | point  |
+---------------------------------------------------+
| 1    |  70          |  80       |  A     | 12     |
+---------------------------------------------------+
| 2    |   60         |  70       | B      | 11     |
+---------------------------------------------------+

得分表

+---------------------------------------+
| no      |  exam   |  code    | score  |
+---------------------------------------+
|1000     |   1     | 121      | 70     |
+---------------------------------------+
|1000     |    1    | 231      | 80     |
+---------------------------------------+
|1001     |     1   | 121      |  56    |
+---------------------------------------+
|1001     |    1    |  231     |  85    |
+---------------------------------------+    

我正在

错误消息

Mysql ERROR 1111 (HY000): Invalid use of group function

我认为错误来自于带有条款的等式,但我不知道如何解决它。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

首先,将每位学生的考试成绩加起来以获得总数:

SELECT `no`, SUM(score) AS total, 100*COUNT(`code`) AS outof
FROM scores
WHERE exam=1
GROUP BY `no`

然后,将该查询的结果加入评分:

SELECT s.`no`, s.total, s.outof, g.grad, g.point
FROM (
    SELECT `no`, SUM(score) AS total, 100*COUNT(`code`) AS outof
    FROM scores
    WHERE exam=1
    GROUP BY `no`
) s
JOIN gradings g ON s.total/s.outof*100 BETWEEN g.range_begin AND g.range_end
WHERE s.`no`=1000;