![](/img/trans.png)
[英]PHP/MySQL - Select all the rows where column from table 1 is equal to column from table 2
[英]How to select all from MySQL table where column between dates and order by column
我正在做一个项目,为学习中心建立评估领导小组。 我有一张桌子,看起来像这样
我正在尝试编写一个查询,该查询将按CLASS在DATE范围内从表中选择所有查询,为每个STUDENT_ID添加得分,然后按添加得分的降序排列以创建排行榜。 我已经阅读了一些有关子查询的内容,但对示例或它们的工作方式还不太了解,我还认为我需要在查询中使用SELECT DISTINCT student_id,但是我的知识也很有限,因为我只使用过一次。
无论如何,这是我到目前为止所拥有的。
$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>';
}
}
}
但是我需要它来添加SCORE并通过查询中添加的SCORE进行排序,而这是我用编写的代码无法实现的。
我知道应该开始使用PDO而不是mysql_query,这又使知识有限,并且我的时间已经用完了。 所有反馈将不胜感激。 哦,分数确实是一个百分比。
您不需要子查询,只需要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
我认为GROUP BY
可以解决问题,因为您正尝试将单个STUDENT_ID的所有分数相加。
如果我错了,请随时纠正我,但是下面的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.