[英]How to select all from MySQL table where column between dates and order by column
I am working on a project to build an assessment leader board for a learning centre. 我正在做一个项目,为学习中心建立评估领导小组。 I've got a table that looks like this
我有一张桌子,看起来像这样
I am trying to write a query which will select all from the table by CLASS, within DATE range, add score per individual STUDENT_ID and then order in descending order by the added score to create the leader board. 我正在尝试编写一个查询,该查询将按CLASS在DATE范围内从表中选择所有查询,为每个STUDENT_ID添加得分,然后按添加得分的降序排列以创建排行榜。 I've read a little on sub queries but can't quite understand the examples or exactly how they work, I also think I would need a SELECT DISTINCT student_id in my query but my knowledge here is also limited as I have only used it once.
我已经阅读了一些有关子查询的内容,但对示例或它们的工作方式还不太了解,我还认为我需要在查询中使用SELECT DISTINCT student_id,但是我的知识也很有限,因为我只使用过一次。
Anyway this is what I have so far. 无论如何,这是我到目前为止所拥有的。
$classcheck = mysql_query("SELECT *
FROM assessment
WHERE class = '$class_info'
order by score DESC")
or die(mysql_error());
if(mysql_num_rows($classcheck) > 0){
while($row = mysql_fetch_array($classcheck)){
if(strtotime($row["date"]) > strtotime($fromdate) && strtotime($row["date"]) < strtotime($todate)){
echo $row['score'].'<p>';
}
}
}
But I need it to add SCORE and order by the added SCORE in the query somewhere which I cannot achieve with what I have written. 但是我需要它来添加SCORE并通过查询中添加的SCORE进行排序,而这是我用编写的代码无法实现的。
I know should start using PDO rather than mysql_query, knowledge limited again and I am running out of time. 我知道应该开始使用PDO而不是mysql_query,这又使知识有限,并且我的时间已经用完了。 All feedback would be greatly appreciated.
所有反馈将不胜感激。 OH, and the score is really a percentage.
哦,分数确实是一个百分比。
You don't need a subquery, you just need SUM
and GROUP BY
to total the scores by student, and a WHERE
clause to restrict the dates. 您不需要子查询,只需要
SUM
和GROUP BY
即可按学生计算总分,并需要WHERE
子句来限制日期。
SELECT student_name, SUM(score) AS total_score
FROM assessment
WHERE date BETWEEN '$fromdate' AND '$todate'
AND class = '$class_info'
GROUP BY student_id
ORDER BY total_score DESC
I think a GROUP BY
might do the trick since you are trying to add up all the scores of an individual STUDENT_ID. 我认为
GROUP BY
可以解决问题,因为您正尝试将单个STUDENT_ID的所有分数相加。
Please feel free to correct me if I'm wrong but the following SQL should get you what you are looking for. 如果我错了,请随时纠正我,但是下面的SQL应该可以为您提供所需的信息。
SELECT SUM(score) AS ttl_score, student_name
FROM assessment
WHERE class='$class_info'
AND date>='$start' AND date<='$end'
GROUP BY student_id ORDER BY ttl_score DESC;
$classcheck = mysql_query("Select Student_id, sum(Score) as SummedScore from assessment where class='$class_info' and
date between '$fromdate' and '$todate' Group by Student_ID Order By SummedScore"
or die(mysql_error());
if(mysql_num_rows($classcheck) > 0){
while($row = mysql_fetch_array($classcheck)){
echo $row['SummedScore'].'<p>';}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.