繁体   English   中英

如何在某些条件下从mysql表获取字段的最大值和平均值

[英]How to get maximum and average of a field from mysql table with some conditions

我有一张桌子,上面有类似下面的记录。


id     score      student_id      course_id
----   ------     ----------      ----------
1      12         1               1
2      10         2               1
3      20         3               1
4      35         1               2
5      50         5               1
6      70         1               3
7      25         3               2
8      30         2               2
9      25         3               3

目前,我先运行此查询


SELECT id,
       score,
       student_id,
       course_id
FROM scores
WHERE student_id=1
查询的输出是

SELECT AVG(score) AS avg_score,
         MAX(score) AS max_score
  FROM scores WHERE course_id = RESULT['course_id']

然后在结果上运行LOOP并使用此查询查找avg_score,max_score


id  student_id   course_id  score  avg_score  max_score
--  ----------   ---------  -----  ---------  ---------
1   1            1          12     23         50
4   1            2          35     30         35
6   1            3          70     47.50      70

然后将它们添加到结果中。 所以最后我用avg_score和max_score这样的结果

 id student_id course_id score avg_score max_score -- ---------- --------- ----- --------- --------- 1 1 1 12 23 50 4 1 2 35 30 35 6 1 3 70 47.50 70 

我想知道是否有可能使用单个查询而不是我现在正在执行的结果。

我已经尝试过该查询,但是我只得到1行而不是3行。而且avg_score和max_score是错误的。


id  student_id   course_id  score  avg_score  max_score
--  ----------   ---------  -----  ---------  ---------
1   1            1          12     30.78      70

上面查询的输出是

 id student_id course_id score avg_score max_score -- ---------- --------- ----- --------- --------- 1 1 1 12 30.78 70 

sqlfiddle链接为http://sqlfiddle.com/#!2/8a3f1f/8

如果使用单个查询无法实现,但是比我现在做的更好的选择,请告诉我。

PS:这是实际问题的jsfiddle链接。 http://sqlfiddle.com/#!2/c50aa9/1/0它有两个表。 我将两个表简化并合并为一个问题。 我正在尝试的单个查询仅给出一行,应该像这样的查询给出4行,但没有avg_score和max_score http://sqlfiddle.com/#!2/c50aa9/3/0

SELECT id, score, student_id, course_id,  
       AVG(score) as avg_score, 
       MAX(score) as max_score
FROM scores 
WHERE student_id = 1
group by id, score, student_id, course_id 

如果您删除了where条件,那么您可以一次为所有学生获得此条件。

以下查询解决了难题。


SELECT Score.id, Score.student_id, Score.course_id, Score.score, ROUND(AVG(mScore.score),2) as avg_score, MAX(mScore.score) as max_score 
FROM `scores` AS `Score` 
LEFT JOIN `scores` as `mScore` ON mScore.course_id = Score.course_id 
WHERE Score.student_id = 1 GROUP BY Score.id

http://sqlfiddle.com/#!2/8a3f1f/10

如果还有更好的解决方案,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM