MYSQL SUM GROUP BY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1598700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MYSQL SUM GROUP BY
提问by Stephane
I'm working on a high school grading system.
我正在研究高中评分系统。
At my school, grades can be changed by reworking problems and I store these changes with dates.
在我的学校,成绩可以通过重做问题来改变,我将这些改变与日期一起存储。
I have a function that properly returns averages because the most recent grade is flagged with a "current" field with a value of '1'. I'd like to make the function capable of returning the most recent grade with respect to a date in the past. I'm making a graph of how their average has changed over time.
我有一个函数可以正确返回平均值,因为最近的成绩被标记为“当前”字段,其值为“1”。我想让该函数能够返回关于过去日期的最新成绩。我正在绘制他们的平均值如何随时间变化的图表。
What I'd like to do is something like this:
我想做的是这样的:
select sum(grades.points)
from grades
where date < 'thedate'
order by date DESC
group by assignmentID
I can't use sum and group by. It errors...
我不能使用 sum 和 group by。它错误...
The best I can think of is to do a sub-select. Any other thoughts?
我能想到的最好的方法是做一个子选择。还有其他想法吗?
回答by OMG Ponies
GROUP BY has to come before ORDER BY:
GROUP BY 必须在 ORDER BY 之前:
SELECT SUM(g.points)
FROM GRADES g
WHERE g.date < 'thedate'
GROUP BY g.assignmentid
ORDER BY g.date DESC
回答by Gaurang
Try this:
尝试这个:
SELECT cat_name, SUM(amount) AS total_amount
FROM table
GROUP BY cat_name