MAX,SUM然后AVG所有在一个SQL查询?

时间:2014-02-05 22:04:09

标签: mysql sql database

此处需要复杂的SQL查询,不确定它是否可行。

我有一张这样的表:

------------------------
|uid |lesson_id |score |
------------------------
|1   |0         |20    |
|1   |0         |25    |
|1   |0         |15    |
|1   |0         |40    |
|1   |1         |70    |
|1   |0         |10    |
|1   |1         |20    |
|1   |1         |55    |
|1   |1         |55    |
|1   |0         |5     |
|1   |2         |65    |
------------------------

对于特定用户,我需要获得每节课的最高分数,将它们相加,然后在单个SQL查询中获得它们的平均值。

最高分数:

-----------------------
|lesson_id |max_score |
-----------------------
|0         |40        |
|1         |70        |
|2         |65        |
-----------------------

和:

------
|sum |
------
|175 |
------

平均:

-------
|avg  |
-------
|58.3 |
-------

这是怎么回事?

SELECT uid AS id, AVG(max_score) AS avg_score FROM 
    (
    SELECT uid, lesson_id, max(score) AS max_score FROM cdu_user_progress 
    WHERE session_id = $session_id
    GROUP BY uid, lesson_id 
) AS tt 
WHERE uid IN ($ids) 
GROUP BY uid 
ORDER BY avg_score

5 个答案:

答案 0 :(得分:2)

您可以使用子查询:

SELECT uid, SUM(MaxScore), Avg(MaxScore) 
FROM
(
  SELECT uid, lesson_id,max(score) as MaxScore
  FROM scores 
  GROUP BY userid, lesson_id 

) AS m
GROUP BY  uid

或仅针对一位用户:

SELECT SUM(MaxScore), Avg(MaxScore) 
FROM
(
  SELECT lesson_id,max(score) as MaxScore
  FROM scores 
  WHERE uid = $uid
  GROUP BY lesson_id 
) AS m

或“一群特定用户”:

$uidlist = (comma-delimited list of user ids)

SELECT uid, SUM(MaxScore), Avg(MaxScore) 
FROM
(
  SELECT uid, lesson_id,max(score) AS MaxScore
  FROM scores 
  WHERE FIND_IN_SET(uid, $uidlist)
  GROUP BY uid, lesson_id 
) AS m
GROUP BY uid

答案 1 :(得分:1)

以下是一个简单的示例 SQLFIDDLE

select Avg(tt.maxscores) from (
select lesson_id,max(score) as maxscores
from t
group by lesson_id ) as tt

答案 2 :(得分:0)

SELECT AVG( s.scores ) AS avarage, SUM( s.scores ) AS total
FROM (

SELECT lesson_id, MAX( score ) AS scores
FROM  `tblScores` 
GROUP BY lesson_id
) AS s

答案 3 :(得分:0)

您可以在单个SQL查询中轻松执行此操作,但您需要使用多个语句

最简单的是,您可以通过子查询执行此操作,但可以通过临时表或Common-Table-Expression完成相同的结果。

(另请注意,SQL AVG函数已经对结果进行求和并将结果除以。您不希望执行AVG(SUM(X)),因为它最终会产生无意义的数字。 )无论如何,举个例子:

首先,编写一个SQL表达式来获取您将要平均的项目,例如每个用户的每个测试的最高分数。

SELECT MAX(Score) As MaxScore, uid, lesson_id
FROM table
GROUP BY uid, lesson_id

然后,您将上面的SELECT视为一个表,并在其周围进行第二次选择以获得每个uid的平均最高得分。

SELECT AVG(MaxScore) as Final, uid 
FROM (
    SELECT MAX(Score) As MaxScore, uid, lesson_id
    FROM table
    GROUP BY uid, lesson_id
) AS subQuery
GROUP BY uid

您可以使用此方法轻松添加其他聚合函数,因为它非常标准,因此可以在大多数SQL服务器中使用。但是,根据供应商的不同,您可能需要使用自定义语法来执行此操作,例如OVER and Parition by in SQL Server

答案 4 :(得分:-1)

一切皆有可能,它可能非常非常难看。这是一个丑陋的代码示例,可以在单个查询中获得您想要的内容......

PSEUDO 代码查询:

SELECT lesson_id, max_score WHERE uid=X
UNION
SELECT -1, sum //done via nested query
UNION
SELECT -2, average //done via nested query