0

我有一个 MySQL 表,其中记录了回答问题的用户以及试验次数。就像是:

username trials
-------- ------
user1    10
user2    7
user1    20

等等。从中我可以计算出他们回答问题的次数(COUNT)。现在我想计算平均试验次数,即得到下表:

username avg
-------- ---
user1    15
user2    7

我试过这个查询:

SELECT(a.totalguess/b.totalknow) as avg FROM( SELECT username, SUM(trials) AS totalguess FROM thetable GROUP BY username) a, (SELECT username, COUNT(*) as totalknow FROM thetable GROUP BY username)b WHERE a.username=b.username;

它只给了

avg
---
15
7

八九不离十!但没有知情者。我可能可以将它们与 php 结合起来,但我想要一个纯 MySQL 解决方案。所以我该怎么做?提前致谢!

4

5 回答 5

3
SELECT username as knower, AVG(trials) as theavg
FROM mytable
GROUP BY username

会给你这个:

knower, theavg

user1, 15
user2, 7
于 2013-01-15T19:05:03.257 回答
2
SELECT a.knower, (a.totalguess/b.totalknow) as avg 
FROM (SELECT knower, SUM(trials) AS totalguess FROM thetable GROUP BY knower) a, 
     (SELECT knower, COUNT(*) as totalknow FROM thetable GROUP BY knower)b 
WHERE a.knower=b.knower;

或者简单地说:

SELECT knower, SUM(trials)/COUNT(*) as avg -- or you can just use AVG(trials)
FROM thetable 
GROUP BY knower
于 2013-01-15T19:01:37.593 回答
1

您可以在一个查询中执行此操作:

      SELECT knower, SUM(trials)/count(*)
      from thetable
      group by knower
于 2013-01-15T19:04:15.680 回答
0

您的初始 SELECT 语句确定将返回哪些列。现在你有

SELECT(a.totalguess/b.totalknow) as avg FROM ...

所以你只会得到一个名为“avg”的列。因此,将知道者添加到您的选择列表中。

SELECT a.knower as knower,
       (a.totalguess/b.totalknow) as avg
FROM
...
于 2013-01-15T19:04:07.317 回答
0
SELECT knower, AVG(trials) FROM thetable GROUP BY knower
于 2013-01-15T19:04:43.617 回答