正在开发学校报告卡系统。
学生可以完成14个学科,但是在评分时,系统应选择最佳的8个主题,并总结8个主题的点。该系统使用这笔款项对学生进行评分。我试图使用点ASC的顺序和限制8,此显示最佳的8个主题,但是总而言之,它总结了学生所做的所有主题的点。
有什么问题?
SELECT stid, subid, total, point FROM oresults WHERE stid= '2' ORDER BY point ASC;
+-------+-------+-------+
| subid | total | point |
+-------+-------+-------+
| 3 | 78.5 | 1 |
| 10 | 71.5 | 2 |
| 12 | 65 | 4 |
| 9 | 61 | 4 |
| 4 | 62.5 | 4 |
| 5 | 56.5 | 5 |
| 8 | 55 | 6 |
| 14 | 52 | 6 |
| 6 | 50.5 | 6 |
| 1 | 45 | 8 |
| 11 | 31.5 | 9 |
| 13 | 39.5 | 9 |
| 7 | 37.5 | 9 |
| 2 | 28.5 | 9 |
+-------+-------+-------+
SELECT stid, subid, total, point FROM oresults WHERE stid= '2' ORDER BY point ASC LIMIT 8;
+-------+-------+-------+
| subid | total | point |
+-------+-------+-------+
| 3 | 78.5 | 1 |
| 10 | 71.5 | 2 |
| 12 | 65 | 4 |
| 9 | 61 | 4 |
| 4 | 62.5 | 4 |
| 5 | 56.5 | 5 |
| 8 | 55 | 6 |
| 14 | 52 | 6 |
+-------+-------+-------+
SELECT sum(point) FROM oresults WHERE stid= '2' ORDER BY point ASC LIMIT 8;
+------------+
| SUM(point) |
+------------+
| 82 |
+------------+
- 列表项目
您似乎误解了'限制'限制的工作,'limit'的限制,您并不是在限制组中的结果数,而是将学生人数限制为返回。但是,您可以这样构建这样的查询:
SELECT SUM(point) FROM
(SELECT point FROM oresults WHERE stid= '2' ORDER BY point ASC LIMIT 8) ss
sqlfiddle
使用窗口功能有更优雅的解决方案,不需要您一次只看一个学生。根据您的MySQL版本,它们可能会或可能不起作用,它们将在MySQL的较新版本上使用,但不支持ROW_NUMBER()
或OVER()
。
Select stid, subid, total, point, SUM(point) OVER(partition by stid) as pointSum
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY stid ORDER BY point DESC) rowNum FROM report_card) ss
WHERE rowNum<=8
这将为您提供前8行,并带有额外的列,点是前8行中的点的总和,每个stid。
。sqlfiddle
如果您每个stid只有一排,则只需使用ID和Total,就可以做到这一点
SELECT stid, SUM(point) as pointSum
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY stid ORDER BY point DESC) rowNum FROM report_card) ss
WHERE rowNum<=8
GROUP BY stid
sqlfiddle